sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Behavioural differences between `sql.Named` with query vs `NamedExecContext` cause `UPDATE` error

Open koalazub opened this issue 2 years ago • 2 comments

Tools: |-----| | go 1.21 | | github.com/gorilla/schema v1.2.1 | | github.com/jmoiron/sqlx v1.3.5 |

I'm currently getting an error when using named parameters for my Azure SQL Database.

Contrived, but when performing the following:

	updateQry := `UPDATE tblIdNumber SET
    Cust1 = @Cust1
WHERE IdNumber = @IdNumber 
`

	_, err := d.DB.NamedExecContext(ctx, updateQry, docket)
	if err != nil {
		slog.Error("couldn't update IdNumber", err)
		return err
	}

I get an error:

mssql: Must declare the scalar variable "@Cust1"."

Yet when I do:

	updateQry := `UPDATE tblIdNumber SET
    Cust1 = @Cust1
WHERE IdNumber = @IdNumber 

	_, err := d.DB.ExecContext(ctx, updateQry,
		sql.Named("Cust1", Person.Cust1),
	)
	if err != nil {
		slog.Error("couldn't update docket", err)
		return err
	}

It correctly updates the table.

I had the expectation that it removed the need to explicitly state each named parameter but that doesn't seem to be the case in this context. I am pretty new to sqlx, so I'm not sure if I'm missing something here. I did see that there were some fixes to named params in #406 for SQL Server

koalazub avatar Mar 05 '24 04:03 koalazub

I am also having this issue. I was hoping to pass a struct to NamedExec() and use @p1, @p2, @p... placeholders however this gives me the same error, Must declare the scalar variable @p1

bwmarrin avatar Jun 17 '24 20:06 bwmarrin

I am also having this issue. I was hoping to pass a struct to NamedExec() and use @p1, @p2, @p... placeholders however this gives me the same error, Must declare the scalar variable @p1

Yeah I couldn't figure out a solution for it and just typed each field out unfortunately. Wasn't fun considering the size of the thing

koalazub avatar Jun 18 '24 11:06 koalazub