Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to obtain upsert results ? #730

Closed
MathieuNls opened this issue Mar 31, 2022 · 1 comment
Closed

How to obtain upsert results ? #730

MathieuNls opened this issue Mar 31, 2022 · 1 comment

Comments

@MathieuNls
Copy link

Hello,

Thanks for your driver !

I followed code examples from https://sqlperformance.com/2020/09/locking/upsert-anti-pattern and particularly this one:

BEGIN TRANSACTION;
 
UPDATE dbo.t WITH (UPDLOCK, SERIALIZABLE) SET val = @val WHERE [key] = @key;
 
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.t([key], val) VALUES(@key, @val);
END
 
COMMIT TRANSACTION;

To get the id being upserted I used:

Declare @ID TABLE(InnerID INT null);
UPDATE dbo.t WITH (UPDLOCK, SERIALIZABLE) SET val = @val 
OUTPUT inserted.id INTO @ID # I also tried without the INTO
 WHERE [key] = @key;
 
IF @@ROWCOUNT != 0
  SELECT InnerID from @ID;
ELSE
BEGIN
  INSERT dbo.t([key], val) VALUES(@key, @val);
  select SCOPE_IDENTITY() as InnerID;
END

I tried to put this query with and without a prepared statement and through Exec, Query, and QueryRow and with and without sql.Named("ID", sql.Out{Dest: &reportID}), but I was never able to get back the ID.

In SQL Server Management Studio the above query returns one line with one col called InnerID for update and insert.

I am no expert in T-SQL and am new to this driver. There's something I likely don't understand / doing wrong.

Thanks for your help.

@MathieuNls
Copy link
Author

Replacing Select InnerID from @ID by Select * from @ID is the solution to have Query correctly get the row.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant