WEB开发网
开发学院数据库MSSQL Server SQL Server数据库中使用触发器经验谈 阅读

SQL Server数据库中使用触发器经验谈

 2007-05-15 09:26:58 来源:WEB开发网   
核心提示: CREATE VIEW CustomersView ASSELECT * FROM CustomersGerUNIONSELECT * FROM CustomersMexGO创建一个在上述视图上的INSTEAD OF触发器:CREATE TRIGGER Customers_Update2O
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表以及被更新的表,来确定是否更新了多行以及如何执行触发器动作。

上一页  1 2 3 4 

Tags:SQL Server 数据库

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接