Ms Sql插入触发器以影响其他表

时间:2017-12-19 13:05:01

标签: sql-server database sql-server-2008 triggers

我在插入table b时尝试设置table a值,但对table b没有任何影响。就像没有trigger一样。你有什么建议吗?我试过下面但没有结果。

alter trigger triggername on tablea after insert as
begin
update tablea set valuetablea_a = valuetablea_b where id = (select distince id from inserted)
end

begin 
update tableb set valuetableb_a = (select valuetablea_a from tablea where id = (select distincd id from Inserted))
where date = (select distinct date from Inserted)
end

1 个答案:

答案 0 :(得分:0)

试试这个:

ALTER TRIGGER triggername ON tablea AFTER INSERT AS
BEGIN

UPDATE a 
SET 
    valuetablea_a = I.valuetablea_b
    FROM tablea A
        INNER JOIN inserted I
            ON A.Id = I.Id

UPDATE B
    SET
        valuetableb_a = A.valuetablea_a 
        FROM tableb  B
            INNER JOIN tablea 
            ON 1=1 AND EXISTS
            (
                SELECT 1 FROM inserted WHERE ID = A.ID AND [Date] = B.DATE
            ) 
end

在第一次更新中,您正在提供此

update tablea set valuetablea_a = valuetablea_b

这意味着从TableA更新已更新的每一行的值valuetablea_b到valuetablea_a的值。而不是从Updated valuetablea_b列

获取值

2nd Update通过匹配更新记录中的Id和Date fileds来更新TableB.valuetableb_a中的值