-1

我正在尝试实现一个 SQL Server 触发器,以在使用 if 条件在表 A 中更新时更新表 B 中的行。

表一:

id_AA
status
desc1
desc2

表 B:

id_BA
desc3
desc4

逻辑是这样的:

if user update table A set status == success
update B: when id_BA == id_AA
set desc3 = desc1
desc4 = desc2
4

1 回答 1

1

我不是 100% 清楚你的逻辑,但我认为你正在寻找这样的东西:

CREATE TRIGGER dbo.TableA_Update 
ON dbo.TableA
FOR UPDATE
AS
BEGIN
    UPDATE  TableB
    SET     Desc3 = i.Desc1,
            Desc4 = i.Desc2
    FROM    TableB b
            INNER JOIN inserted i           
                ON i.ID_AA = b.ID_BA        -- MATCH CRITERIA IN QUESTION
                AND i.Status = 'success'    -- NEW STATUS IS "SUCCESS"
            INNER JOIN deleted d
                ON d.ID_AA = i.ID_AA
                AND d.Status != 'success'   -- PREVIOUS STATUS WAS NOT "SUCCESS"
END

编辑

如果没有相应的行,TableB您可能要考虑使用MERGE

CREATE TRIGGER dbo.TableA_Update 
ON dbo.TableA
FOR UPDATE
AS
BEGIN
    ;WITH Updated AS
    (   SELECT  i.ID_AA, i.Desc1, i.Desc2
        FROM    inserted i
                INNER JOIN deleted d
                    ON d.ID_AA = i.ID_AA
                    AND d.Status != 'success'   -- PREVIOUS STATUS WAS NOT "SUCCESS"
        WHERE   i.Status = 'success'
    )
    MERGE INTO TableB USING Updated ON ID_AA = ID_BA
    WHEN MATCHED THEN
        UPDATE
        SET Desc3 = Desc1,
            Desc4 = Desc2
    WHEN NOT MATCHED THEN
        INSERT (ID_BA, Desc3, Desc4) VALUES (ID_AA, Desc1, Desc2);
END
于 2012-09-25T14:28:35.303 回答