0

I have a trigger if I do multiple insert then I get an error on:

IF((SELECT FACTREGELPRIJS FROM inserted) > 0)

This is my trigger:

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

How can I fix it? thank you

1
  • You need to use aggregate(max(...)) for if condition and you have to join to inserted pseudo-table to perform updates. Remember that triggers are fired for entire set of changes, not for every record. Commented Mar 1, 2016 at 11:36

1 Answer 1

1

You cannot compare a column with a scalar value. Your query should return a scalar value not a column.

For example something like this:

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

For checking price do this:

IF((SELECT SUM(FACTREGELPRIJS) FROM inserted)> 0)
Sign up to request clarification or add additional context in comments.

7 Comments

What are you checking in if statement ?
I can't instert invoice price, if price > 0 error, The price is based on quantity, price and discount
so you are checking if any row was inserted or not. Am i right?
Each row is a new invoice. should column "price" are checked. Which should not be greater than 0
i need a check every insert row, not all inserted rows together
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.