I’ve having trouble getting a TSQL trigger to even work correctly. I’ve run it through the debugger and it’s not setting any of the variables according to SQL Server Management Studio. The damnedest thing is that the trigger itself is executing correctly and there are no errors when it is executed (just says ‘execution successful’).
The code is as follows (it’s a work in progress…. just getting my self familiar):
USE TestDb
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'OfficeSalesQuotaUpdate' AND type = 'TR')
DROP TRIGGER OfficeSalesQuotaUpdate
GO
CREATE TRIGGER OfficeSalesQuotaUpdate
ON SalesReps
AFTER UPDATE, DELETE, INSERT
AS
DECLARE @sales_difference int, @quota_difference int
DECLARE @sales_original int, @quota_original int
DECLARE @sales_new int, @quota_new int
DECLARE @officeid int
DECLARE @salesrepid int
--UPDATE(Sales) returns true for INSERT and UPDATE.
--Not for DELETE though.
IF ((SELECT COUNT(*) FROM inserted) = 0)
SET @salesrepid = (SELECT SalesRep FROM deleted)
ELSE
SET @salesrepid = (SELECT SalesRep FROM inserted)
--If you address the @salesrepid variable, it does not work. Doesn't even
--print out the 'this should work line.
PRINT 'This should work...' --+ convert(char(30), @salesrepid)
IF (@salesrepid = NULL)
PRINT 'SalesRepId is null'
ELSE
PRINT 'SalesRepId is not null'
PRINT convert(char(50), @salesrepid)
SET @officeid = (SELECT RepOffice
FROM SalesReps
WHERE SalesRep = @salesrepid)
SELECT @sales_original = (SELECT Sales FROM deleted)
SELECT @sales_new = (SELECT Sales FROM inserted)
--Sales can not be null, so we'll remove this later.
--Use this as a template for quota though, since that can be null.
IF (@sales_new = null)
BEGIN
SET @sales_new = 0
END
IF (@sales_original = 0)
BEGIN
SET @sales_original = 0
END
SET @sales_difference = @sales_new - @sales_original
UPDATE Offices
SET Sales = Sales + @sales_difference
WHERE Offices.Office = @officeid
GO
So, any tips? I’ve completely stumped on this one. Thanks in advance.
Your main problem seems to be that there is a difference between
@foo = NULLand@foo IS NULL:The ‘This should work’ PRINT statement doesn’t work because concatenating a NULL with a string gives a NULL, and
PRINT NULLdoesn’t print anything.As for actually setting the value of @salerepid, it seems most likely that the inserted and/or deleted table is in fact empty. What statements are you using to test the trigger? And have you printed out the COUNT(*) value?
You should also consider (if you haven’t already) what happens if someone changes more than one row at once. Your current code assumes that only one row is changed at a time, which may be a reasonable assumption in your environment, but it can easily break if someone bulk loads data or does other ‘batch processing’.
Finally, you should always mention your MSSQL version and edition; it can be relevant for some syntax questions.