2011-06-03 30 views
0

之間的孩子我有一個看起來像兩個表如下:克隆記錄,並劃分了他們兩個

Foo 
--- 
FooID FooType 
----- ------- 
1  Red 
2  Red 
3  Green 
4  Red 
5  Blue 
6  Red 

Bar 
---  
BarID BarFooID BarData 
----- -------- ------- 
1  1   A 
2  1   B 
3  2   C 
4  2   D 
5  3   E 
6  3   F 
7  3   G 
8  3   H 

BarID的6和7被誤用FooID3相關,應該已經與相關不同的美孚,與不同的美孚類型。我有BarID-6 & 7在一個單獨的表中列出(BadBar)

我希望做的是FooID-3複製到一個新的記錄(FooID-7),然後重新指向BarID-6 & 7的BarFooID在FooID-7,然後將FooID-7的FooType更新爲新值。

我的預期了放會是這個樣子:

Foo 
--- 
FooID FooType 
----- ------- 
1  Red 
2  Red 
3  Green 
4  Red 
5  Blue 
6  Red 
7  Purple  // new row 

Bar 
---  
BarID BarFooID BarData 
----- -------- ------- 
1  1   A 
2  1   B 
3  2   C 
4  2   D 
5  3   E 
6  7   F  // updated 
7  7   G  // updated 
8  3   H 

我能想象如何在僞代碼做到這一點:

For Each Bar in BadBars 
    copy Bar's Foo to a new Foo 
    remember the new Foo's FooID 
    update the new Foo's FooType 
    update Bar's BarFooID to the remembered FooID 
End For 

有沒有一種方法,我可以創建一個SQL事務做這個作爲一個操作,或者至少克隆Foo並將Bar重新連接到克隆(我總是可以第二次更新克隆)。

還是我堅持寫一個一個腳本爲此?

+1

尚不清楚,如果你的SQL Server或MS Access中的腳本?如果SQL Server然後是什麼版本? – 2011-06-04 08:34:11

+0

真的,我更感興趣的是要確定是否有一種方法可以將其作爲單個SQL事務執行(實際上是基於插入到另一個表中的更新)。 SQL/Acccess是一個紅鯡魚的位。 – BIBD 2011-06-06 14:27:44

回答

0

使用表變量進行表設置以便於測試。我假設FooID和BarID是標識列。

declare @Foo table 
(
    FooID int identity primary key, 
    FooType varchar(10) 
) 

declare @Bar table 
(
    BarID int identity primary key, 
    BarFooID int, 
    BarData char(1) 
) 
declare @BadBar table 
(
    BarID int 
) 

插入示例數據。該語法同樣適用於SQL Server 2008中:

insert into @Foo values 
('Red'), 
('Red'), 
('Green'), 
('Red'), 
('Blue'), 
('Red') 

insert into @Bar values 
(1, 'A'), 
(1, 'B'), 
(2, 'C'), 
(2, 'D'), 
(3, 'E'), 
(3, 'F'), 
(3, 'G'), 
(3, 'H') 

insert into @BadBar values 
(6), 
(7) 

腳本:

-- Variable to hold the the new FooID 
declare @NewFooID int 

-- Copy FooID 3 to new Foo row 
insert into @Foo (FooType) 
select FooType 
from @Foo 
where FooID = 3 

-- Capture the new auto created FooID 
set @NewFooID = scope_identity() 

-- Update BarFooID in Bar for all BarID in BadBar with new FooID 
update B 
set BarFooID = @NewFooID 
from @Bar as B 
    inner join @BadBar as BB 
    on B.BarID = BB.BarID 

-- Change FooType for newly created Foo 
-- This step is not really necessary because you could 
-- use 'Purple' in the insert statement above instead 
update @Foo 
set FooType = 'Purple' 
where FooID = @NewFooID