我正在寻找一个触发器,该触发器会在关闭位时自动将表格出价中的最高价格插入到表格中?'从0变为1。
我得到的表具有值(Objectnumber,endprice(null),closed?(bit)(非null,默认为0))。
表格以值(对象编号,欧元(出价),用户名)
出价这就是我现在所拥有的,
CREATE TRIGGER AF5 ON objects
FOR INSERT, UPDATE
AS
BEGIN
DECLARE @objectnumber numeric(10)
DECLARE @endprice numeric(7,2)
DECLARE @closed? bit
SET @objectnumber = (SELECT objectnumber from inserted)
SET @endprice =(SELECT endprice from inserted)
SET @closed? =(SELECT closed? from inserted)
IF EXISTS (
SELECT subjectnumber
FROM inserted
WHERE closed? = 1 AND endprice = NULL
)
BEGIN
PRINT ('Found')
update objects set endprice = (
SELECT MAX(b.euro)
from bids b INNER JOIN objects v
on @objectnumber = b.objectnumber
where @closed? = 1
)
END
ELSE
BEGIN
RAISERROR ('Error', 1, 1)
ROLLBACK
END
END
GO
我一直在犯的错误是 消息512,级别16,状态1,过程AF5,行8 [批次启动行3834] 子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
答案 0 :(得分:1)
inserted
表可以包含多行。
我删除你的if条件,因为在IF
内更新后触发器可以再次触发。如果需要,请检查@@ROWCOUNT
变量以获取更新行的计数,并将其与inserted
表中的行数进行比较
CREATE TRIGGER AF5 ON objects
FOR INSERT, UPDATE
AS
BEGIN
IF @@ROWCOUNT = 0 RETURN
UPDATE O
SET endprice = B.EndPrice
FROM Objects O
INNER JOIN inserted I on O.objectnumber = I.objectnumber
CROSS APPLY (
SELECT EndPrice = MAX(B.euro)
FROM bids B
WHERE B.objectnumber = O.objectnumber
) B
WHERE I.[Closed?] = 1 AND I.endprice IS NULL AND B.EndPrice IS NOT NULL
END