Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE OUTPUT into a variable

Tags:

sql-server

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. 
like image 327
Cory Nelson Avatar asked May 30 '13 23:05

Cory Nelson


People also ask

How do you assign a variable to an output in SQL?

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.

What is the output of UPDATE query?

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.

Can you UPDATE a table variable?

It is true you can't update a table variable directly using its variable name - you have to use an alias.


1 Answers

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  
like image 83
Arpit Jain Avatar answered Oct 13 '22 01:10

Arpit Jain