1

i need to create an Update Trigger, that will only work when my record's status is different then the last status recorded.

so i have this right now:

    for UPDATE
AS 
begin try
INSERT INTO tblHistorySource(*)
select *
from [DELETED]
end try

but i need to shomehow check if tblHistorySource.status not equal to delete.status and only then copy the data....

Taryn
  • 242,637
  • 56
  • 362
  • 405
Madam Zu Zu
  • 6,437
  • 19
  • 83
  • 129

3 Answers3

4

You'll want to be careful that you're working on a set of data and not just one record at a time:

INSERT INTO tblHistorySource
SELECT *
FROM DELETED INNER JOIN
     INSERTED ON <<DELETED.PK = INSERTED.PK>>
WHERE DELETED.StatusValue <> INSERTED.StatusValue;

The join condition <<DELETED.PK = INSERTED.PK>> will need to be adapted to your schema, as will the real name of StatusValue.

If StatusValue is nullable (thanks Alex), use this instead:

WHERE DELETED.StatusValue <> INSERTED.StatusValue
   OR DELETED.StatusValue IS NULL AND INSERTED.StatusValue IS NOT NULL
   OR DELETED.StatusValue IS NOT NULL AND INSERTED.StatusValue IS NULL;

Which could probably be simplified using an ISNULL() wrapper, but I'd need to know the data type.

Yuck
  • 49,664
  • 13
  • 105
  • 135
  • If statusValue is nullable, you need to trace changes from NULL to a not NULL values, and vice versa – A-K Jul 22 '11 at 19:02
1

Just add:

IF ((SELECT Status FROM Delted) <> SELECT Status FROM Inserted))
BEGIN
...
END
JNK
  • 63,321
  • 15
  • 122
  • 138
-2

You can do something like this:

DECLARE @statusOldValue status_type
DECLARE @statusNewValue status_type

SELECT @statusOldValue = status FROM deleted

SELECT @statusNewValue= status FROM inserted

IF (@statusOldValue<>@statusNewValue) THEN
BEGIN
 -- Do what you want
END

If you can have situations in which more than one register are updated at the same time then you need to put WHERE clausules to the SELECT statements and put them in iterations in order to treat all the registers.

Doliveras
  • 1,794
  • 2
  • 14
  • 30
  • 3
    Bad trigger. Do not use. You cannot assume there will be only one record in inserted or deleted. – HLGEM Jul 22 '11 at 18:29
  • 1
    This is a very common mistake: you are assuming that only one row can be updated – A-K Jul 22 '11 at 18:59
  • @HLGEM,As I explained on the text, if you have the possibility of multiple updates on a single query, you have to put all this on a iteration to treat all rows, that way it will work with as many updates as you can have. – Doliveras Jul 25 '11 at 16:40
  • you never use iteration in trigger. What if someone updated a million rows? – HLGEM Jul 25 '11 at 17:24