我正在尝试开发一个SQL Server触发器但是当我更新与触发器关键字值具有相同值的记录时,它似乎为我抛出了一个错误,但如果它只是一个匹配该值的记录,那么并没有抛出错误。
错误代码:
关于我为SNL开发的触发器,它似乎产生了一个错误:子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。声明已经终止。
触发码:
USE [TestTrigger]
GO
/****** Object: Trigger [dbo].[TestTrigger] Script Date: 06/04/2015 08:29:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[TestTRigger]
ON [dbo].[SN_Contact2]
FOR INSERT,UPDATE
AS
BEGIN
DECLARE @IDSTATUS varchar(254)
DECLARE @CONTACTID VARCHAR(36)
DECLARE @CLIENTURL nvarchar(254)
set @CONTACTID = (select contact_contactid from inserted)
set @IDSTATUS = (select contact_category from inserted)
set @CLIENTURL = (select CUST_1004 from inserted)
IF @IDSTATUS = 'Client'
BEGIN
update sn_contact2 set CUST_ID_Status_Change_Date = getdate()
where CUST_Main_Contact = 'X' and cust_id_status_change_date is null
and CUST_1004 = @CLIENTURL
END
END
有什么想法吗?
答案 0 :(得分:2)
这些是错误行..当通过单个查询更新/插入多于1条记录时,您将收到此错误(因为子查询返回的值超过1 ..)。
set @CONTACTID = (select contact_contactid from inserted)
set @IDSTATUS = (select contact_category from inserted)
set @CLIENTURL = (select CUST_1004 from inserted)
将您的更新查询从单行更新更改为:
update sn_contact2 set CUST_ID_Status_Change_Date = getdate()
where CUST_Main_Contact = 'X' and cust_id_status_change_date is null
and CUST_1004 --= @CLIENTURL
in (
select CUST_1004 from inserted where contact_category = 'Client'
)