如何在视图上创建而不是更新触发器?

时间:2013-12-27 17:51:21

标签: sql sql-server

我有三个表客户,供应商和供应商。该视图具有以下定义。

CREATE VIEW VW_COMPANY_PHONELIST
AS
SELECT 'Customer' as Source
, CustomerID
, CustomerNumber
, CustomerLastName
, CustomerFirstName
, PhoneNo
FROM Customer
UNION ALL
SELECT 'Supplier' as Source
, SupplierID
, SupplierNumber
, SupplierLastName
, SupplierFirstName
, PhoneNo
FROM Supplier
UNION ALL
SELECT 'Vendor' as Source
, VendorID
, VendorNumber
, VendorLastName
, VendorFirstName
, PhoneNo
FROM Vendor

需要在视图上创建一个而不是更新触发器,以便用户只能使用视图来更新手机号

1 个答案:

答案 0 :(得分:1)

这可能就是你要找的东西。

    CREATE TRIGGER trUp_VW_COMPANY_PHONELIST on VW_COMPANY_PHONELIST
    INSTEAD OF UPDATE
    AS
    BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from 
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      update c set 
        c.phoneno = i.phoneno
      from 
        inserted i
        inner join customers c on i.customerid = c.customerid
      where
        i.source = 'customer'

      update s set 
        s.phoneno = i.phoneno
      from 
        inserted i
        inner join suppliers s on i.customerid = s.supplierid
      where
        i.source = 'supplier'

      update v set 
        v.phoneno = i.phoneno
      from 
        inserted i
        inner join vendor v on i.customerid = v.vendorid
      where
        i.source = 'vendor'

    END
    GO

这不是经过测试的代码。