我一直在研究如何创建一个可以处理多个更新/插入的TSQL触发器。
我们有来自多个来源的数据,我的目标是在更新/插入之前验证/更正这些数据。
我写了一个适用于单行数据的触发器。
我正在努力弄清楚如何让它来处理多行数据。
CREATE TRIGGER [dbo].[tr_GPTitleToGov]
ON [dbo].[GoverningPersons]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Title1 VARCHAR(15)
DECLARE @UBI VARCHAR(9)
DECLARE @ETPID CHAR(4)
DECLARE @Ident INT
SET @Title1 = (SELECT Title1 FROM INSERTED)
SET @UBI = (SELECT UBI FROM INSERTED)
SET @ETPID = (SELECT [ETPID] FROM [entity] WHERE @UBI = [entity].[UBI])
SET @Ident = (SELECT Ident FROM INSERTED)
IF ((@Title1 = 'Executor') OR (@Title1 = 'Incorporator'))
BEGIN
IF @ETPID IN ('0143', '0147', '0148', '0150', '0152', '0154')
UPDATE GoverningPersons
SET [Title1] = 'Executor',
[Title2] = NULL,
[Title3] = NULL,
[Title4] = NULL
WHERE Ident = @Ident;
ELSE
UPDATE GoverningPersons
SET [Title1] = 'Incorporator',
[Title2] = NULL,
[Title3] = NULL,
[Title4] = NULL
WHERE Ident = @Ident;
END
ELSE
UPDATE GoverningPersons
SET [Title1] = 'Governor',
[Title2] = NULL,
[Title3] = NULL,
[Title4] = NULL
WHERE Ident = @Ident;
END
我认为扔我的是加入字段的位置,以便我可以根据不同表格中的数据检查数据。
我以前从未写过触发器,所以任何帮助都会受到赞赏。
答案 0 :(得分:3)
font-lock-ensure
触发器每行执行一次 NOT ,而是作为基于集合的操作执行,因此对整个DML操作执行仅ONCE 。因此,您需要像使用join语句的任何其他更新日期一样对待它。只有您可以使用特殊的CREATE TRIGGER [dbo].[tr_GPTitleToGov]
ON [dbo].[GoverningPersons]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE gp
SET Title1 = CASE
WHEN i.Title1 IN ('Incorporator','Executor')
AND e.ETPID IN ('0143', '0147', '0148', '0150', '0152', '0154') THEN 'Executor'
WHEN i.Title1 IN ('Incorporator','Executor') THEN 'Incorporator'
ELSE 'Governor'
END
,Title2 = NULL
,Title3 = NULL
,Title4 = NULL
FROM
GoverningPersons gp
INNER JOIN inserted i
ON gp.Ident = i.Ident
LEFT JOIN entity e
ON i.UBI = e.UBI
END
和inserted
表。以上是更新触发器的示例,应该为您提供一些指导。