3

誰かが私を助けてくれることを願っています。同じテーブルの行をコピーしたいのですが、そのテーブルには別のテーブルとの関係があり、それに応じて関連する行をコピーする必要があります:

表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

次のように、Table1 Id に応じて Table2 にも同じことをしたいと思います。

表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 を持っています。私は最初の部分を行う方法を知っていますが、2 番目の部分で立ち往生しています。

4

1 に答える 1

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
于 2012-11-28T06:04:14.900 に答える