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
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
INSERTstatement that insert 50 rows.Therefore, your statements like this:
will fail miserably.
You need to re-write your trigger to take this into account – the
Insertedtable 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: