【问题标题】:Insert record in two tables with identity field value from first table在具有来自第一个表的标识字段值的两个表中插入记录
【发布时间】:2016-03-12 21:32:21
【问题描述】:

我们如何在 SQL Server 的同一个存储过程中的两个表中插入记录。我只需要从第一个表中插入 ID 字段即可将其作为对第二个表的引用插入。在多用户环境中,我们将有并发插入。

【问题讨论】:

标签: sql-server


【解决方案1】:
BEGIN TRAN

    DECLARE @id INT

    INSERT INTO tbl1
    VALUES (..)

    SET @id = SCOPE_IDENTITY()

    INSERT INTO tbl2
    VALUES (@id)

COMMIT TRAN

【讨论】:

    【解决方案2】:
    begin tran
    Declare @tbl table (id int)
    
    insert into t11
    output inserted.* into @tbl
    select 1
    
    
    insert into t2
    select * from @tbl
    commit
    

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多