简体   繁体   English

SQL SERVER 2008获得最后的插入值

[英]SQL SERVER 2008 GET LAST INSERTED VALUES

This is my table. 这是我的桌子。

Ticket(id int auto_increment,name varchar(50));

after inserting into this table i want send id and name to mail.. how can i get the last Inserted value. 插入此表后,我希望发送id和邮件名称..如何获取最后一个Inserted值。

help to solve this... 有助于解决这个问题......

Look into: Scope_identity 请看: Scope_identity

SCOPE_IDENTITY()

The table which is having Identity Property from that table we can get the last inserted record id will be like this 从该表中获取标识属性的表我们可以得到最后插入的记录ID将是这样的

SELECT SCOPE_IDENTITY()

OR 要么

But this is not a safe technique: 但这不是一种安全的技术:

SELECT MAX(Id) FROM Ticket

OR 要么

This is also not a safe technique: 这也不是一种安全的技术:

SELECT TOP 1 Id FROM Ticket ORDER BY Id DESC

You should use SCOPE_IDENTITY() to get last primary key inserted value on your table. 您应该使用SCOPE_IDENTITY()来获取表上的最后一个主键插入值。 I guess it should be the ID value. 我想它应该是ID值。 Once you have it, do a SELECT using this ID and there you have it. 一旦你拥有它,使用这个ID做一个SELECT ,你有它。

There is also @@IDENTITY but there are some differences using one or the another that could lead to inaccuracies on the values. 还有@@IDENTITY但是使用一个或另一个可能导致值不准确的一些差异。

Check these detailed articles for more insights, a detailed description on how to use them, why they are different and some demo code: 查看这些详细文章以获取更多见解,有关如何使用它们的详细说明,它们的不同之处以及一些演示代码:

For SQL Server before 2008 R2 Service Pack 1 ( Link ): 对于2008 R2 R2 Service Pack 1( 链接 )之前的SQL Server:

You may receive incorrect values when using SCOPE_IDENTITY() and @@IDENTITY 使用SCOPE_IDENTITY()和@@ IDENTITY时,您可能会收到不正确的值

In that case, the OUTPUT clause is the safest mechanism: 在这种情况下,OUTPUT子句是最安全的机制:

DECLARE @InsertedRows AS TABLE (Id int)
DECLARE @NewId AS INT
INSERT INTO HumanResources.Employees
  ( /* column names */)
OUTPUT Inserted.Id INTO @InsertedRows
  VALUES (/* column values */)
SELECT @NewId = Id FROM @InsertedRows

在你的表中添加auto increement字段,比如.... index(INT,AUTO INCREEMENT)然后在插入或任何操作完成之前c通过获取max(index)得到你的最后一条记录

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

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