Database : SQL Server 2008
数据库:SQL Server 2008
Is there a way to have an insert statement return a value in SQL Server,
有没有办法让insert语句在SQL Server中返回一个值,
There is a similar question in
有类似的问题
Return a value from a insert statement , which talks about ORACLE .
从insert语句返回一个值,该语句讨论ORACLE。
I don't work with databases much, and not aware of ORACLE/SQL Server much, so sorry to ask it all over again.
我没有太多使用数据库,也没有太多了解ORACLE / SQL Server,所以很遗憾再次问到它。
For simplicity let me provide a small example :
为简单起见,我举一个小例子:
The table EmpDetails
has EmpiD
and EmpName
. The value of EmpID
is autogenerated by the database.
表EmpDetails有EmpiD和EmpName。 EmpID的值由数据库自动生成。
INSERT INTO EMPDETAILS VALUES("John")
Now I want to get the value of EmpID
associated with John
现在我想获得与John关联的EmpID的值
I don't want a stored procedure, I want a SQL statement only .
我不想要存储过程,我只想要一个SQL语句。
1 个解决方案
#1
7
Yes - you can use the little known and little used OUTPUT clause in your INSERT statement
是的 - 您可以在INSERT语句中使用鲜为人知且很少使用的OUTPUT子句
INSERT INTO dbo.YourTable(col1, col2, col3, ...., ColN)
OUTPUT Inserted.Col1, Inserted.Col5, Inserted.ColN
VALUES(val1, val2, val3, ....., valN)
This returns a normal set of data, that you can deal with as you need to.
这将返回一组正常的数据,您可以根据需要处理这些数据。
As the MSDN docs show, you can also send the OUTPUT values into e.g. a table variable or temp table for later use, if you need to.
正如MSDN文档所示,您还可以将OUTPUT值发送到例如如果需要,可以使用表变量或临时表供以后使用。
To answer your updated question, use this:
要回答您更新的问题,请使用以下命令:
INSERT INTO dbo.EMPDETAILS(EmpName)
OUTPUT Inserted.EmpID
VALUES("John")
#1
7
Yes - you can use the little known and little used OUTPUT clause in your INSERT statement
是的 - 您可以在INSERT语句中使用鲜为人知且很少使用的OUTPUT子句
INSERT INTO dbo.YourTable(col1, col2, col3, ...., ColN)
OUTPUT Inserted.Col1, Inserted.Col5, Inserted.ColN
VALUES(val1, val2, val3, ....., valN)
This returns a normal set of data, that you can deal with as you need to.
这将返回一组正常的数据,您可以根据需要处理这些数据。
As the MSDN docs show, you can also send the OUTPUT values into e.g. a table variable or temp table for later use, if you need to.
正如MSDN文档所示,您还可以将OUTPUT值发送到例如如果需要,可以使用表变量或临时表供以后使用。
To answer your updated question, use this:
要回答您更新的问题,请使用以下命令:
INSERT INTO dbo.EMPDETAILS(EmpName)
OUTPUT Inserted.EmpID
VALUES("John")