如何在插入后捕获唯一标识符

时间:2014-07-15 19:10:14

标签: sql sql-server

我必须在加入表的现有表中创建新的电子邮件记录我想更新一个表示这是新记录的字段。

示例:

INSERT INTO dbo.email.email (dbo.email.eml_address, dbo.email.eml_customer_key)
SELECT new_email, new_customer_key
FROM NEW_TABLE

Update dbo.email_ext
Set dbo.email_ext.new_eml = '1'
Where dbo.email_ext.eml_key_ext = 'Recently create key from insert statement shown above'

2 个答案:

答案 0 :(得分:4)

您需要使用SCOPE_IDENTITY()值,它将包含刚刚创建的记录的ID,但只包含一个。

假设您正在处理一条记录:

DECLARE @ID INT

INSERT INTO dbo.email (eml_address, eml_customer_key)
SELECT new_email, new_customer_key
FROM NEW_TABLE

SET @ID = SCOPE_IDENTITY()

Update dbo.email_ext
Set new_eml = '1'
Where eml_key_ext = @ID

如果要插入倍数,则需要将列表输出到表格中(在本例中为表格变量),您可以一次更新它们。

DECLARE @myIDs TABLE (NEWID INT)

INSERT INTO dbo.email (eml_address, eml_customer_key)
OUTPUT inserted.ID INTO @myIDs 
SELECT new_email, new_customer_key
FROM NEW_TABLE

Update t
Set new_eml = '1'
from dbo.email_ext t
join @myIDs m
   on t.eml_key_ext = m.ID

答案 1 :(得分:2)

使用OUTPUT子句捕获自动生成的id / guids / defaults / etc.

CREATE TABLE #test (
  id int identity(1,1) primary key,
  uid uniqueidentifier DEFAULT NEWID(),
  value varchar(max)
)

INSERT #test (value)
OUTPUT inserted.*
SELECT 'test'


id          guid                                 value
----------- ------------------------------------ ---------
1           72B70577-2679-4C2A-A575-62D30807B9D2 test

(1 row(s) affected)