2012-11-27 30 views
2

希望有人能帮助我,我想复制在同一个表行和表有关系到另一个表,我必须相应地复制相关行:SQL复制行与关系表

表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 

我想这样做,以表2依赖于表1 IDS是这样的:正如你所看到的行

表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。 我知道如何做第一部分,但我坚持在第二部分。

+0

看一看[使用merge..output得到source.id和target.id之间的映射( http://stackoverflow.com/questions/5365629/using-merge-output-to-get-mapping-between-source-id-and-target-id) –

回答

0

谢谢您的回答,我想通了这样的购买使用输出和身份:

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