【问题标题】:How to capture the unique identifier after the insert [duplicate]如何在插入后捕获唯一标识符[重复]
【发布时间】:2014-09-06 02:58:03
【问题描述】:

我必须在连接表中的现有表中创建新的电子邮件记录我想更新一个字段,表明这是一条新记录。

例子:

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'

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您需要使用 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
    

    【讨论】:

      【解决方案2】:

      使用 OUTPUT 子句捕获自动生成的 ids/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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-04
        • 2012-08-12
        • 2013-10-18
        • 1970-01-01
        • 2013-04-13
        • 2013-10-01
        相关资源
        最近更新 更多