我有一个SQL MERGE脚本,用于更新存在更新触发器的表。 当MERGE脚本只有一个表更新时,触发器工作正常。当MERGE命令附带对表的多个更新时,触发器返回错误。 这是触发器:
ALTER TRIGGER [dbo].[userupd]
ON [dbo].[users]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @navn varchar(255), @fornavn varchar(255), @efternavn varchar(255),@initialer varchar(255), @areagroups varchar(255)
SET @fornavn = (SELECT Fornavn FROM DELETED)
SET @efternavn = (SELECT Efternavn FROM DELETED)
SET @initialer = (SELECT Initialer FROM DELETED)
IF @initialer IS NULL SET @initialer = 'Extern'
SET @navn = @fornavn + ' ' + @efternavn + ' (' + @initialer + ')'
SET @areagroups = (SELECT AddedAreaGroups FROM NOX.dbo.simscodesusers WHERE Username = @navn)
SELECT @areagroups OriginalString, RTRIM(LTRIM(@areagroups)) TrimmedValue
SET @areagroups = ' ' + @areagroups
INSERT INTO NOX.dbo.SIMScodesAutoUpdate
( Action ,
Username
)
SELECT 'DELETE' ,
D.Fornavn + ' ' + D.Efternavn + ' (' + D.Initialer + ')'
FROM DELETED D;
INSERT INTO NOX.dbo.SIMScodesAutoUpdate
( Action ,
Username ,
NoxAutoCode ,
NoxAutoCodePIN ,
UserGroup ,
Startdate ,
EndDate ,
AddedAreaGroups
)
SELECT 'ADD' ,
I.Fornavn + ' ' + I.Efternavn + ' (' + I.Initialer + ')' ,
I.Kortnummer ,
I.PINkode ,
I.Brugerniveau ,
I.Startdato ,
I.Slutdato,
@areagroups
FROM INSERTED I
END
这是从包含MERGE脚本的SQL作业返回的错误:
Executed as user: CPCORP\SQDKRTV96service. Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. [SQLSTATE 21000] (Error 512) The statement has been terminated. [SQLSTATE 01000] (Error 3621).
步骤失败。
是否可以编辑触发器以处理多个值?
提前致谢。
答案 0 :(得分:4)
在第二种情况下(“当MERGE命令带有多个更新......”时)DELETED
表包含许多行。因此,您无法将MULTI行表分配给ONE SCALAR变量。这是错误的来源'子查询返回的值超过1 ......':
SET @fornavn = (SELECT Fornavn FROM DELETED)
Microsoft: Create DML Triggers to Handle Multiple Rows of Data