SQL Server 2000中的触发器使用(续)

示例

   在本例中,创建了一个德国客户表和一个墨西哥客户表。放置在视图上的INSTEAD OF触发器将把更新操作重新定向到适当的基表上。这时发生的插入是对CustomersGer表的插入而不是对视图的插入。

   创建两个包含客户数据的表:

SELECT * INTO CustomersGer FROM Customers WHERE Customers.Country = 'Germany'
SELECT * INTO CustomersMex FROM Customers WHERE Customers.Country = 'Mexico'

GO

   在该数据上创建视图:

CREATE VIEW CustomersView AS
SELECT * FROM CustomersGer
UNION
SELECT * FROM CustomersMex
GO

   创建一个在上述视图上的INSTEAD OF触发器:

CREATE TRIGGER Customers_Update2

ON CustomersView

INSTEAD OF UPDATE AS

DECLARE @Country nvarchar(15)

SET @Country = (SELECT Country FROM Inserted)

IF @Country = 'Germany'

BEGIN

UPDATE CustomersGer

SET CustomersGer.Phone = Inserted.Phone

FROM CustomersGer JOIN Inserted

ON CustomersGer.CustomerID = Inserted.CustomerID

END

ELSE

IF @Country = 'Mexico'

BEGIN

UPDATE CustomersMex

SET CustomersMex.Phone = Inserted.Phone

FROM CustomersMex JOIN Inserted

ON CustomersMex.CustomerID = Inserted.CustomerID

END

   通过更新视图,测试触发器:

UPDATE CustomersView SET Phone = ' 030-007xxxx'
WHERE CustomerID = 'ALFKI'

SELECT CustomerID, Phone FROM CustomersView
WHERE CustomerID = 'ALFKI'

SELECT CustomerID, Phone FROM CustomersGer
WHERE CustomerID = 'ALFKI'

   那么具体的讲,对于多列数据,如何计算方差呢?:

CREATE TRIGGER [calT1T2T3] ON dbo.DCLB
FOR INSERT,UPDATE
AS
update P
SET
/**//*
计算方差的触发器
*/
P.T1=(I.P1+I.P2+I.P3+I.P4+I.P5+I.P6),
P.T2=(I.Y1+I.Y2+I.Y3+I.Y4+I.Y5+I.Y6 ),
P.T3=SQRT(P.T1*P.T1+P.T2*P.T2)

FROM DCLB AS P INNER JOIN Inserted AS I
ON P.SID = I.SID

   触发器的使用很方便,而且也很简单,重要的是理解inserted过程。可将UPDATE语句看成两步操作:即捕获数据前像(before image)的DELETE语句,和捕获数据后像(after image)的INSERT语句。当在定义有触发器的表上执行UPDATE语句时,原始行(前像)被移入到deleted表,更新行(后像)被移入到inserted表。触发器检查deleted表和inserted表以及被更新的表,来确定是否更新了多行以及如何执行触发器动作。

你可能感兴趣的:(MS-SQL文章)