SQL复制行与关系中的行

时间:2012-11-27 03:25:51

标签: sql sql-server tsql copy rows

希望有人可以帮助我,我想在同一个表中复制行,并且该表与另一个表相关,我必须相应地复制相关行:

表1

       table1Id table0Id otherColumn 
          1         3        8
          2         3        9
          3         4        6

我复制了table0Id = 3

的行

表1

       table1Id table0Id otherColumn 
          1         3        8
          2         3        9
          3         4        6
        -------------------------
          4         3        8
          5         3        9

我想对Table2做同样的事情,这取决于Table1 ID这样:

表2

       table2Id table1Id otherColomn
           1        1        0
           2        2        5
           3        3        8

表2

       table2Id table1Id otherColomn
           1        1        0
           2        2        5
           3        3        8
         -----------------------
           4        4 new Id 0
           5        5 new Id 5

如您所见,第1行和第2行在table2中复制,但它们在table1中新添加的行中有新ID。 我知道如何做第一部分,但我被困在第二部分。

1 个答案:

答案 0 :(得分:1)

感谢您的回答,我认为这就像使用输出和身份购买一样:

Declare @temp table(tempId int,tempName nchar(10),tempOther bit, rownumber int identity)
insert into @temp select Id,Nam,other from dbo.Table_1  where Nam = 'ToCopy'

Declare @tempIds table(outputId int,rownumber int identity)

Declare @finalTemp table(OldId int,new_id int)

select * from dbo.Table_1
select * from dbo.Table_2

insert into dbo.Table_1
output inserted.Id into @tempIds
select tempName,tempOther from @temp


insert into @finalTemp
select oldT.tempId, newT.outputId 
from @temp as oldT
join @tempIds as  newT on oldT.rownumber = newT.rownumber

insert into dbo.Table_2(Table1Id)
select ftemp.new_id
from dbo.Table_2 t2 
join @finalTemp ftemp on ftemp.OldId = t2.Table1Id


select * from dbo.Table_1
select * from dbo.Table_2