Reputation: 3827
I have a SQL trigger that triggers on a table update. When the table is updated it modifies some fields in another table.
It seems to be working but I am not sure if the way I set status is correct (if inserted contains multiple rows). I tested it and got the correct answer (but still I suspect that this is not the correct/best way).
CREATE TRIGGER [dbo].[myTrigger]
ON [dbo].[myTable]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
declare @OldStatus int
declare @NewStatus int
select @OldStatus = [currentStatus] FROM INSERTED
if @OldStatus = 1 or @OldStatus = 3 or @OldStatus = 5
begin
set @NewStatus = 1
end
if @OldStatus = 8 or @OldStatus = 9
begin
set @NewStatus = 8
end
if @OldStatus = 11 or @OldStatus = 12 or @OldStatus = 13
begin
set @NewStatus = 11
end
UPDATE myNewTable SET [LastModifiedDate] = GETDATE(),
[Status] = @NewStatus,
[Type] = inserted.Type
FROM inserted
WHERE ([id] = inserted.id)
END
I'd think the correct solution would be something like:
UPDATE myNewTable SET [LastModifiedDate] = GETDATE(),
[Status] = ***<add logic here>***,
[Type] = inserted.Type
FROM inserted
WHERE ([id] = inserted.id)
Upvotes: 3
Views: 68
Reputation: 16137
You need something like this:
CREATE TRIGGER [dbo].[myTrigger]
ON [dbo].[myTable]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE
myNewTable
SET
LastModifiedDate=GETDATE(),
Status=
CASE
WHEN i.currentStatus IN (1,3,5) THEN 1
WHEN i.currentStatus IN (8,9) THEN 8
WHEN i.currentStatus IN (11,12,13) THEN 11
ELSE NULL -- if the current status isn't in the cases above
END,
Type=i.Type
FROM
myNewTable AS mnt
INNER JOIN inserted AS i ON
i.id=mnt.id;
END
Upvotes: 1