0

I'm trying to get the last id inserted into a table. I was using

SELECT IDENT_CURRENT('TABLE')

But the problem is that it doesn't return the last inserted id, it returns the max inserted id.

For example, if i do:

INSERT INTO 'TABLA' (ID) VALUES (100)

SELECT IDENT_CURRENT('TABLE') returns 100

but then if i do

INSERT INTO 'TABLA' (ID) VALUES (50)

SELECT IDENT_CURRENT('TABLE') returns 100

and I want to get 50

I need the ID of a specific table, and I generate the id dinamically, so it's not an identity How can i do it?

4

3 回答 3

5

从您的代码中,看起来 ID 不是标识(自动增量)列,因此 IDENT_CURRENT 不会按照您的预期进行。

如果要查找插入的最后一行,则需要一个表示插入时间的 datetime 列,然后可以执行以下操作:

SELECT TOP 1 [ID] FROM TABLEA ORDER BY [InsertedDate] DESC

编辑:一些附加说明:

  • 您的 InsertedDate 列应该默认设置为 GetDate() 除非您的应用程序、存储过程或您用于执行插入的任何内容将负责设置该值
  • 我说您的 ID 不是身份/自动增量的原因是因为您正在向其中插入一个值。这只有在您关闭身份插入时才有可能。
于 2013-11-02T18:27:52.957 回答
1

SQL Server does not keep track of the last value inserted into an IDENTITY column, particularly when you use SET IDENTITY_INSERT ON;. But if you are manually specifying the value you are inserting, you don't need SQL Server to tell you what it is. You already know what it is, because you just specified it explicitly in the INSERT statement.

If you can't get your code to keep track of the value it just inserted, and can't change the table to have a DateInserted column with a default of CURRENT_TIMESTAMP (which would allow you to see which row was inserted last), perhaps you could add a trigger to the table that logs all inserts.

于 2013-11-02T19:00:51.843 回答
1
SELECT SCOPE_IDENTITY()

将返回当前会话中插入的最后一个值。
编辑
然后你正在做的最好的方法就是确保 ID 列是一个 IDENTITY 列,IDENT_CURRENT('Table_name')、@@IDENTITY 和 SCOPE_IDENTITY() 返回由 Identity 列生成的最后一个值。
如果 ID 列不是标识列,则所有这些函数都将返回 NULL。

于 2013-11-02T18:27:44.720 回答