【问题标题】:How to get ID from one table and associate with record in another table in SQL Server如何从一个表中获取 ID 并与 SQL Server 中另一表中的记录关联
【发布时间】:2013-09-05 15:45:48
【问题描述】:

我已尝试寻找此问题的答案,但无济于事。这种设置方式背后没有很好的逻辑。这家伙不知道他在做什么,但这是我必须与之合作的(长话短说)。

我正在使用 SQL Server 2008R2 我需要从一个表中获取记录并将数据传输到 4 个单独的表中,所有这些表都具有一对一的关系(我知道 - 不聪明)。我需要从插入数据的第一个表中的 Identity 字段中获取值,然后使用相同的 ID 填充其他 3 个表并相应地分散数据。例如:

旧表:Field1、Field2、Field3、Field4

NewTable1:标识字段,Field1 新表 2:ID、字段 2 新表 3:ID、字段 3 NewTable4:ID、Field4

我想在存储过程中处理这个问题。我想做一个循环,但我读到 SQL 中的循环是不可取的。

Loop moving through each record in OldTable... (??)

INSERT INTO NewTable1
  (Field1)
Select Field1 from OldTable

   INSERT INTO NewTable2
     (ID, Field2)
   Select SCOPE_IDENTITY?, Field2 From OldTable Where OldTable.ID = ??

   etc for other 2 tables

Loop to next record in OldTable

我不确定如何使用 SCOPE_IDENTITY,但我感觉这将涉及我如何完成此任务。

另外,每当在 NewTable1 中创建新记录时,我可能需要设置一个触发器。我知道,这很疯狂,但我对此无能为力,只能解决它。

所以,我需要知道 1:最初填充表格的最佳方式 2:如何为新记录做触发器

1 的解决方案可能涉及 2。

请帮忙!

【问题讨论】:

  • OldTable 中的任何列或列组合是主键还是唯一的?
  • 是的,我想我可以使用那个 PK 来关联它们。但是,该字段并未存储在新表中。什么是我可以使用它的好方法?

标签: sql-server identity


【解决方案1】:

您可以使用合并语句的输出子句来获取OldTable 中的现有主键和NewTable1 中新生成的身份ID 之间的映射。

-- Temp table to hold the mapping between OldID and ID
create table #ID
(
  OldID int primary key,
  ID int
);

-- Add rows to NewTable1 and capture the ID's in #ID
merge NewTable1 as T
using OldTable as S
on 1 = 0
when not matched by target then
  insert(Field1) values(S.Field1)
output S.ID, inserted.ID into #ID(OldID, ID);

-- Add rows to NewTable2 using #ID to get the correct value for each row
insert into NewTable2(ID, Field2)
select I.ID, O.Field2
from #ID as I
  inner join OldTable as O
    on I.OldID = O.ID

insert into NewTable3(ID, Field3)
select I.ID, O.Field3
from #ID as I
  inner join OldTable as O
    on I.OldID = O.ID

insert into NewTable4(ID, Field4)
select I.ID, O.Field4
from #ID as I
  inner join OldTable as O
    on I.OldID = O.ID

drop table #ID;

SQL Fiddle

另见Using merge..output to get mapping between source.id and target.id

【讨论】:

    【解决方案2】:

    如何使用插入语句的 OUTPUT 子句?假设 Field1 是 OldTable 上的唯一键...

    Declare @IDinserted table(ID int, Field1 varchar(255));
    
    Insert Into NewTable1(Field1)
    Output inserted.ID, inserted.Field1 into @IDinserted
    Select OldID, Field1 from OldTable;
    
    Insert Into NewTable2(RowID, Field2)
    Select i.ID, o.@Field2 
    from @IDinserted i Inner Join OldTable o
      on i.Field1=o.Field1;
    

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 2010-12-31
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多