我有2个表通过CustomerId
建立关系:
发票:
Invoice | RouteCode | CustomerId
1001 | 1 | 90
1002 | 2 | 70
1003 | 3 | 80
客户:
CustomerId | CustomerName | RouteCode
90 | AAA | 1
70 | BBB | 2
80 | CCC | 3
我想创建一个触发器,一旦更改了发票中的RouteCode,将更改特定客户的客户中的路径代码。
示例:
发票:
Invoice | RouteCode | CustomerId
1001 | 2 | 90 (the RouteCode here has changed)
1002 | 2 | 70
1003 | 3 | 80
客户:
CustomerId | CustomerName | RouteCode
90 | AAA | 2 (the RouteCode here must change too)
70 | BBB | 2
80 | CCC | 3
我有这段代码:
create trigger UpdateRouteCode
before update on Invoice
for each row
begin
if :new.RouteCode != :old.RouteCode
then
update Customer c
set c.RouteCode = :new.RouteCode
where c.CustomerId = :new.CustomerId
end
我不知道这是否正确,因为在新的查询窗口中它说:
Msg 102,Level 15,State 1,Procedure UpdateRouteCode,Line 2
“之前”附近的语法不正确。
答案 0 :(得分:3)
create trigger UpdateRouteCode
on Invoices
for update
as
begin
update c
set RouteCode = i.RouteCode
from inserted i
inner join Customers c on i.CustomerId = c.CustomerId
where i.RouteCode <> c.RouteCode
end