I'm trying to perform an update and a select ... basically, update based on an index, and then select the row id that was updated.
This is simple using the OUTPUT clause:
UPDATE Foo SET Bar = 1 OUTPUT INSERTED.Id WHERE Baz = 2
But now, how do I get this into a variable?
DECLARE @id INT
These three don't work:
UPDATE Foo SET Bar = 1 OUTPUT @id = INSERTED.Id WHERE Baz = 2 SET @id = (UPDATE Foo SET Bar = 1 OUTPUT INSERTED.Id WHERE Baz = 2) SET @id = (SELECT Id FROM (UPDATE Foo SET Bar = 1 OUTPUT INSERTED.Id Id WHERE Baz = 2) z)
That last one included because it had me temporarily excited when all the red squigglies went away in Management Studio. Alas, I get this error:
A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed in a SELECT statement that is not the immediate source of rows for an INSERT statement.
You can use @@IDENTITY to get the last inserted id. DECLARE @someInt int INSERT INTO MyTable2(AIntColumn) VALUES(12) SET @someInt = @@IDENTITY; Assuming your table has a primary key which you are looking to set as said variable.
The OUTPUT clause returns the values of each row that was affected by an INSERT, UPDATE or DELETE statements. It even supports the MERGE statement, which was introduced in SQL Server 2008. The result from the OUTPUT clause can be inserted into a separate table during the execution of the query.
It is true you can't update a table variable directly using its variable name - you have to use an alias.
If only one row is affected, it can be done without a table variable.
DECLARE @id INT UPDATE Foo SET Bar = 1, @id = id WHERE Baz = 2 SELECT @id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With