Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign inserted output value to a variable in sql server? [duplicate]

Possible Duplicate:
SQL Server Output Clause into a scalar variable

DECLARE @id int INSERT INTO MyTable(name) OUTPUT @id = Inserted.id VALUES('XYZ') 

I am trying like above. How is it possible?

like image 259
RAKESH HOLKAR Avatar asked Sep 24 '12 13:09

RAKESH HOLKAR


People also ask

How do I assign a result to a variable in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.


1 Answers

Use table variable to get id

DECLARE @id int DECLARE @table table (id int) INSERT INTO MyTable(name) OUTPUT inserted.id into @table VALUES('XYZ')  SELECT @id = id from @table 
like image 144
rs. Avatar answered Oct 05 '22 12:10

rs.