Below is a trigger used on one of our SQL tables for any insert/update action. 99/100 times this trigger works just fine however every now and then we receive this error message:
Cannot insert the value NULL into column 'TransactionDate', table 'AgentResourcesU01.dbo.TransactionLog'; column does not allow nulls.
INSERT fails. The statement has been terminated.
As you can see from the Insert statement, the columns in our transaction log table are TransactionDate, Operator, TableName, Action, TableString and UserId. I set the variable @transDate in the opening SELECT statement so as it appears to me, there should be no way a NULL gets in there unless it's bad data coming in.
Any thoughts?
BEGIN
SELECT @symetraNumber = SymetraNumber, @lastChangeOperator = LastChangeOperator, @transDate = LastChangeDate, @entityType = EntityType,
@firstName = FirstName, @lastName = LastName, @suffix = NameSuffix, @corpName = CorporateName, @controlId = ControlId
FROM inserted
IF @firstName IS NULL SET @firstName = 'NULL'
IF @lastName IS NULL SET @lastName = 'NULL'
IF @suffix IS NULL SET @suffix = 'NULL'
IF @corpName IS NULL SET @corpName = 'NULL'
IF @controlId IS NULL SET @controlId = 'NULL'
SET @tableString = 'SymNum:' + @symetraNumber + ' EntType:' + @entityType + ' Fname:' + @firstName + ' Lname:' + @lastname + ' Suff:' + @suffix +
' CorpName:' + @corpName + ' ctrlId:' + @controlId
INSERT INTO TransactionLog (TransactionDate, Operator, TableName, Action, TableString, UserId)
VALUES (@transDate, 'Op', @tableName, @action, @tableString, @lastChangeOperator)
END
LastChangeDateis not null?Insertedtable only ever contains a single row. That assumption is wrong. The trigger fires once per batch - e.g. if you insert 50 rows at once, your trigger fires once and theInsertedtable will contain 50 rows - so your statements likeSELECT @symetraNumber = SymetraNumber .. FROM insertedwill fail miserably ....