简体   繁体   English

获取最后插入的ID

[英]Get the last inserted ID

I want to get the ID of the last row inserted into a table and use it with a variable in SQL Server. 我想获取插入到表中的最后一行的ID,并将其与SQL Server中的变量一起使用。

Here is my code: 这是我的代码:

SELECT IDENT_CURRENT('profiles')

I tried adding a where clause 我尝试添加where子句

SELECT IDENT_CURRENT('profiles') WHERE profiles.userid = '2'

Here is my error: 这是我的错误:

The multi-part identifier "profiles.userid" could not be bound. 不能绑定多部分标识符“ profiles.userid”。

Your 2nd Query 您的第二个查询

To make the second query with the WHERE clause work ( to the extent that it does not error ), you need to anchor the multi-part identifier profiles.userid with a FROM : 为了使第二个查询使用WHERE子句起作用( 在一定程度上不会出错 ),您需要使用FROM来锚定多部分标识符profiles.userid

SELECT IDENT_CURRENT('profiles') FROM profiles WHERE profiles.userid = '2'

But this does not make a lot of sense because the WHERE clause will not really change the bottom-line result (ie the last identity generated for profile ) - just possibly include it more than once in the result set. 但这没有多大意义,因为WHERE子句不会真正改变底线结果(即,为profile生成的最后一个标识)-可能在结果集中多次包含它。

Back to Your 1st Query 返回您的第一个查询

If you really want to get the last identity value generated for profile to delete the row it identifies, then your first query... 如果您真的想获取为profile生成的最后一个标识值,以删除它标识的行,那么您的第一个查询...

SELECT IDENT_CURRENT('profiles')

...is the direction to go. ...是前进的方向。

Of course, you will then need to employ the last identity value generated for profile in a DELETE statement rather than just a SELECT - for example (assuming that the identity column in profiles is id )... 当然,然后,您将需要使用DELETE语句中为profile生成的最后一个标识值,而不仅仅是SELECT例如(假设profiles中的id )...

DECLARE @lastID int;
SELECT @lastID = IDENT_CURRENT('profiles');

DELETE FROM profiles WHERE id = @lastID;

..., which would really just be better said as: ...,实际上更好的说法是:

DELETE FROM profiles WHERE id = IDENT_CURRENT('profiles');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM