SQL Server:触发句柄多行

时间:2016-03-01 11:31:07

标签: sql-server-2008 tsql

我有一个触发器,如果​​我做多次插入然后我收到错误:

IF((SELECT FACTREGELPRIJS FROM inserted) > 0)

这是我的触发器:

CREATE TRIGGER [dbo].[trg]
ON [dbo].[FACTUURREGEL]
AFTER INSERT
AS
BEGIN
    DECLARE @rowCount INT = @@ROWCOUNT 

    IF(@rowCount = 0)
        RETURN

    BEGIN TRY
        IF(EXISTS(SELECT 1 FROM inserted) 
           AND NOT EXISTS(SELECT 1 FROM deleted))
        BEGIN
            IF((SELECT FACTREGELPRIJS FROM inserted) > 0)
            BEGIN
                RAISERROR('MAG geen prijs toegevoegd worden',16,1)
            END
            ELSE
            BEGIN
                UPDATE f 
                SET FACTREGELPRIJS = (p.PRODUCTPRIJS * f.FACTREGELHOEVEELHEID) - ((p.PRODUCTPRIJS * f.FACTREGELHOEVEELHEID)*(f.FACTREGELKORTING/100.0))
                FROM FACTUURREGEL f
                INNER JOIN PRODUCT p on p.PRODUCTID = f.PRODUCTID
            END
        END
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;

        DECLARE
            @ErrorMessage   VARCHAR(400),
            @ErrorSeverity  INT,
            @ErrorState     INT

        SELECT
            @ErrorMessage   = ERROR_MESSAGE(),
            @ErrorSeverity  = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE()

        RAISERROR (@ErrorMessage , @ErrorSeverity, @ErrorState)
    END CATCH
END

我该如何解决?谢谢

1 个答案:

答案 0 :(得分:1)

您无法将列与标量值进行比较。您的查询应返回标量值而不是列。

例如:

IF((SELECT count(FACTREGELPRIJS) FROM inserted)> 0)

为了查看价格,请执行以下操作:

IF((SELECT SUM(FACTREGELPRIJS) FROM inserted)> 0)