【问题标题】:SCOPE_IDENTITY() multiple insertSCOPE_IDENTITY() 多次插入
【发布时间】:2016-04-28 08:01:56
【问题描述】:

如何避免这些类型我可以为每个身份插入捕获值并在其他表中插入

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

DECLARE @LookupID INT = SCOPE_IDENTITY() 

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, @LookupID, NULL)

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

DECLARE @LookupID2 INT = SCOPE_IDENTITY() 

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, @LookupID2, NULL)

【问题讨论】:

  • 我不明白这里的问题。有什么问题或你想做什么?您可以跳过声明变量,只需将 SCOPE_IDENTITY() 作为列值。
  • 我从第一个获取标识值并将标识插入到同一个表中的第二个语句中。而不是每次声明我可以获得值以便我可以插入多个记录
  • 不,没有“神奇”的方法可以做到这一点 - 你正在做的事情非常好,而且它要走的路..
  • 只要您想继续使用“原始”低级 SQL,这几乎是最好的。使用 ORM(对象关系映射器)会大大提高您的工作效率,可以让您摆脱很多无聊、容易出错的“胶水”您现在需要手动编写的代码。
  • 添加到飞盘的答案:您可以使用 OUTPUT 子句从行中获取任何数据(注意复数。),例如新插入行的标识列值。 OUTPUT 可以与 INSERTUPDATEDELETEMERGE 一起使用,并且在 @ 的情况下提供对 beforeafter 值的访问987654329@。一个非常值得放在口袋里的工具。

标签: sql-server sql-server-2008 tsql sql-server-2005


【解决方案1】:

如果排序顺序是唯一的(我怀疑是)

然后插入所有值 ()、()、() 并使用output 子句

我正是这样做的,但我现在没有时间查找代码

【讨论】:

    【解决方案2】:
    declare @t table 
    (
        id  int not null identity,
        a   int ,
        b   int ,
        c   int ,
        OtherInfo int
    );
    
    
    insert into @t (a, b, c)
    output inserted.a, inserted.b, inserted.c, inserted.id 
    into LookupTables (a, b, c, OtherInfo)
    values (1,1,1),(2,2,2),(3,3,3),(4,4,4),(5,5,5);
    
    select * from @t;
    

    SQL Fiddle

    【讨论】:

      【解决方案3】:

      我想您是在问如何在不为每个最后插入的标识值声明变量的情况下做到这一点。当然,您实际上可以只重用一个变量。但更简单的是完全跳过该变量。

      Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
      Values (a, b, c, d, e, NULL, NULL)
      
      Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
      Values (a, b, c, d, e, SCOPE_IDENTITY(), NULL)
      
      Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
      Values (a, b, c, d, e, NULL, NULL)
      
      Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
      Values (a, b, c, d, e, SCOPE_IDENTITY(), NULL)
      

      【讨论】:

      • 还能简单多少?你有 4 个单独的插件,对吗?不知道还能做些什么来让它“更简单”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多