如何在select-insert语句中跟踪自动生成的id

我有两个桌子细节和头部。详细信息表将首先编写。之后,将编写头表。头部是详细信息表的摘要。我想从细节到头表保持参考。我有一个解决方案,但它不优雅,需要复制求和过程中使用的连接和过滤器。我正在寻找更好的解决方案。以下是我目前拥有的一个例子。在这个例子中,我简化了表结构。在现实世界中,总和非常复杂。
-- Preparation
create table #detail (
      detail_id int identity(1,1)
    , code char(4)
    , amount money 
    , head_id int null
    );

create table #head (
      head_id int identity(1,1)
    , code char(4)
    , subtotal money
    );

insert into #detail ( code, amount ) values ( 'A', 5 );
insert into #detail ( code, amount ) values ( 'A', 5 );
insert into #detail ( code, amount ) values ( 'B', 2 );
insert into #detail ( code, amount ) values ( 'B', 2 );


-- I would like to somehow simplify the following two queries
insert into #head ( code, subtotal )
    select code, sum(amount)
    from #detail
    group by code

update #detail 
  set head_id = h.head_id
from #detail d
  inner join #head h on d.code = h.code

-- This is the desired end result
select * from #detail
详细表的最终结果:   detail_id代码数量head_id   1 A 5.00 1   2 A 5.00 1   3 B 2.00 2   4 B 2.00 2     
已邀请:
从你的主题我会说这个。 你看过OUTPUT子句了吗? 它允许您将ID分配给变量,因此您不需要临时表。 但是从你的身体来看,我真的不明白你在做什么......     
为什么不先插入
head
行,然后在插入
detail
行时连接到头?换句话说,如果您知道将要用于详细记录的不同代码(在您的示例中为A和B),您可以继续将它们插入到
head
表中。然后,您可以在之后插入
detail
记录,连接到head以获得相应代码的
head_id
值。     

要回复问题请先登录注册