在insert语句中需要帮助

时间:2013-07-14 16:06:53

标签: sql sql-server tsql

以下是详细问题: Database diagram

我想将源表t1中的数据填充到目标表t2,t3和t4中。现在, 我正在做什么,首先我插入到t2中:

insert into t2(t2.t2Data0, t2.t2Data1)
select t1.t2Data0,t1.t2.Data1 from t1

现在,为了插入t3和t4,我需要一些可以从t2获取ID col的数据的脚本 来自t1的其余列数据。

任何答案都将不胜感激。感谢

3 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,在将行插入t2之后,您想使用它的标识字段来帮助填充t3和t4吗?

如果是这样,您可以使用JOIN

INSERT INTO t3 
SELECT t2.id, t1.t3Data0
FROM t1 
    INNER JOIN t2 ON t1.t2Data0 = t2.tdData0 AND t1.t2Data1 = t2.tdData1

INSERT INTO t4 
SELECT t2.id, t1.t4Data0
FROM t1 
    INNER JOIN t2 ON t1.t2Data0 = t2.tdData0 AND t1.t2Data1 = t2.tdData1

答案 1 :(得分:1)

insert  t1
        (c1, c2, c3, c4)
select  coalesce(t2.c1, t3.c1, t4.c1)
,       t2.c2
,       t3.c3
,       t4.c4
from    t2
full outer join    
        t3
on      t2.c1 = t3.c1
full outer join    
        t4
on      t2.c1 = t4.c1
        or t3.c1 = t4.c1

答案 2 :(得分:1)

我没有测试,但我看到类似......在t1上的插入触发器之后

a)插入到t2(插入到t2(t2.t2Data0,t2.t2Data1)中选择t1.t2Data0,t2.Data1从t1 join插入t1.id = inserted.id)

b)选择范围标识(选择@ T2ID = SCOPE_IDENTITY()

c)插入到t3(插入到t3(id,t3data0)中选择@ T2ID,t.t3data0从t1连接插入t1.id = inserted.id)

d)插入到t4(插入到t4(id,t4data0)中选择@ T2ID,t.t4data0从t1连接插入t1.id = inserted.id)

CREATE TRIGGER trgName ON [t1] 
FOR INSERT 
AS
    declare @T2ID int
    insert into t2(t2.t2Data0, t2.t2Data1) select t1.t2Data0,t2.Data1 from t1 join inserted on t1.id=inserted.id
    select @T2ID=SCOPE_IDENTITY()
    insert into t3(id, t3data0) select @T2ID, t.t3data0 from t1 join inserted on t1.id=inserted.id
    insert into t4(id, t4data0) select @T2ID, t.t4data0 from t1 join inserted on t1.id=inserted.id
end

当然,假设此方案符合您的需求