2011-06-03 55 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