93

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.

3 Answers 3

122

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 
Sign up to request clarification or add additional context in comments.

7 Comments

I've never even thought of this. Very nice!
Thanks Cory, I wondered if the set keyword inside the update will be able to set a variable and it worked!
will this work with insert for a single affected row?
No @rahoolm, only the SET and SELECT keywords can modify a variable and these keywords cannot be used with INSERT statement
There are some limits to this approach; for example, if you have a rowversion column, this will return the last rowversion, not the one resulting from your update.
|
113

Because an update can affect multiple rows, it requires a table to store its results:

declare @ids table (id int);

UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id INTO @ids
WHERE Baz = 2

If you're sure only one row will be affected, you can pull out the id like:

declare @id int
select  top 1 @id = id
from    @ids

1 Comment

You don't have to have a table for the results. You can do this: OUPUT INSERTED.* Of course this will bring back all the cols though.
12

Alternatively, If only one row is being affected:

DECLARE @id INT

UPDATE Foo 
SET @id = Bar = 1  ---Yes, this is valid!
WHERE Baz = 2

SELECT @id 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.