不使用第二个查询就返回最后插入的ID [英] Return last inserted ID without using a second query
问题描述
我正在使用SQL Server 2008处理ASP.NET项目(C#).
I'm working on an ASP.NET project (C#) with SQL Server 2008.
当我在数据库中的表中插入一行时,我想获取最后插入的ID,即表的 IDENTITY (自动递增).
When I insert a row into a table in the database, I would like to get the last inserted ID, which is the table's IDENTITY (Auto Incremented).
我不希望使用其他查询,而是执行类似的操作...
I do not wish to use another query, and do something like...
SELECT MAX(ID) FROM USERS;
因为-尽管它只是一个查询-感觉很me脚...
Because - even though it's only one query - it feels lame...
当我插入某些内容时,通常会使用 ExecuteNonQuery(),它会返回受影响的行数.
When I insert something I usually use ExecuteNonQuery(), which returns the number of affected rows.
int y = Command.ExecuteNonQuery();
是否有一种方法可以在不使用其他查询的情况下返回最后插入的ID ?
Isn't there a way to return the last inserted ID without using another query?
推荐答案
大多数人是通过以下方式做到这一点的:
Most folks do this in the following way:
INSERT dbo.Users(Username)
VALUES('my new name');
SELECT NewID = SCOPE_IDENTITY();
(或代替查询,将其分配给变量.)
(Or instead of a query, assigning that to a variable.)
所以实际上不是两个针对表的查询 ...
So it's not really two queries against the table...
但是,还有以下方法:
INSERT dbo.Users(Username)
OUTPUT inserted.ID
VALUES('my new name');
尽管如此,您实际上将无法使用 ExecuteNonQuery
来检索它.
You won't really be able to retrieve this with ExecuteNonQuery
, though.
这篇关于不使用第二个查询就返回最后插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!