我正在尝试实现一个SQL Server触发器,以便在表A中使用if条件进行更新时更新表B中的行。
表格A:
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
答案 0 :(得分:2)
我不是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