使用trigger使用参数在另一个表上更新列时更新一个表的列

时间:2016-03-17 03:00:22

标签: sql-server

我有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
  “之前”附近的语法不正确。

1 个答案:

答案 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