0

This gave an error

Msg 156, Level 15, State 1, Procedure Trig_Insert_Serials_Null, Line 30
Incorrect syntax near the keyword 'INSERT'.

Table structure:

Serials (CurrencyId, DivisionId, BranchId, NewSerialNumber, Display, TypeId)

I want to change 0 to null in (CurrencyId, DivisionId, BranchId).

CREATE TRIGGER Trig_Insert_Serials_Null
   ON  Serials
   INSTEAD OF INSERT   
AS 
BEGIN

DECLARE @currencyId int;
DECLARE @branchId int;
DECLARE @divisionId int;

SELECT @currencyId = INSERTED.CurrenceyId FROM INSERTED;
SELECT @branchId = INSERTED.BranchId FROM INSERTED;
SELECT @divisionId = INSERTED.DivisionId FROM INSERTED;

IF @currencyId = 0 
    SET @currencyId = NULL;
END

IF @branchId = 0 
    SET @branchId = NULL;
END

IF @divisionId = 0 
    SET @divisionId = NULL;
END


INSERT INTO Serials (CurrenceyId,DivisionId,BranchId,NewSerialNumber,
                         Display, TypeId)
VALUES (INSERTED.CurrenceyId,INSERTED.DivisionId, INSERTED.BranchId,
         INSERTED.NewSerialNumber, INSERTED.Display,INSERTED.TypeId)

END
GO

2 Answers 2

1

You are assuming that the trigger is fired once per row - this is wrong.

The trigger is fired once per batch and could be fired for a single INSERT statement that insert 50 rows.

Therefore, your statements like this:

SELECT @currencyId = INSERTED.CurrenceyId FROM INSERTED;

will fail miserably.

You need to re-write your trigger to take this into account - the Inserted table can contain one or multiple rows - you cannot just plainly assume it's always a single row.

Basically, you need to do something like this:

 INSERT INTO Serials (CurrenceyId, DivisionId, BranchId, NewSerialNumber, Display, TypeId)
    SELECT
       CASE i.CurrenceyId WHEN 0 THEN NULL ELSE i.CurrenceyId END,
       CASE i.DivisionId WHEN 0 THEN NULL ELSE i.DivisionId END,
       CASE i.BranchId WHEN 0 THEN NULL ELSE i.BranchId END,
       i.NewSerialNumber, i.Display, i.TypeId
    FROM Inserted i
Sign up to request clarification or add additional context in comments.

Comments

1

Remove 3 END s that you have with your 3 IF statements.

END should Start with a BEGIN

You have 4 END s and Only one BEGIN in your trigger

1 Comment

sorry buddy @marc_s answer is better.

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.