从SQL Server 2008中的INSERT语句返回值 [英] Returning a value from an INSERT statement in SQL Server 2008

查看:682
本文介绍了从SQL Server 2008中的INSERT语句返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据库:SQL Server 2008

Database : SQL Server 2008

有一种方法让insert语句在SQL Server中返回一个值,

Is there a way to have an insert statement return a value in SQL Server,

从insert语句中返回一个值,它涉及ORACLE。

Return a value from a insert statement , which talks about ORACLE .

我不使用数据库,

为了简单起见,我提供一个小例子:

For simplicity let me provide a small example :

EmpDetails EmpiD EmpName EmpID 的值由数据库自动生成。

The table EmpDetails has EmpiD and EmpName. The value of EmpID is autogenerated by the database.

INSERT INTO EMPDETAILS VALUES("John")



现在我想获得 EmpID

Now I want to get the value of EmpID associated with John

我不想要一个存储过程,我只想要一个SQL语句。

I don't want a stored procedure, I want a SQL statement only .

解决方案

是的 - 你可以使用一些知名的和小的

Yes - you can use the little known and little used OUTPUT clause in your INSERT statement

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.

如MSDN文档所示,您还可以将OUTPUT值发送到例如

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.

要回答您更新的问题,请使用以下命令:

To answer your updated question, use this:

INSERT INTO dbo.EMPDETAILS(EmpName)
OUTPUT Inserted.EmpID
VALUES("John")

这篇关于从SQL Server 2008中的INSERT语句返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆