Kyl*_*e G 3 sql sql-server triggers
我正在使用 SQL Server 2008 并有以下触发器:
USE [gatordata]
GO
/****** Object: Trigger [dbo].[TriggerUserAssigned] Script Date:2/20/2016 3:42:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[TriggerUserAssigned]
ON [dbo].[User]
AFTER UPDATE
AS
IF UPDATE([AssignedToUser])
BEGIN
declare @Id int;
declare @AssignedToUser nvarchar(50);
declare @TimeStamp datetime;
declare @Hour bit;
declare @RushService bit;
declare @Status nvarchar(50);
select @Id=i.Id from inserted i;
select @AssignedToUser=i.AssignedToUser from inserted i;
select @Hour=i.[Hour] from inserted i;
select @RushService=i.[RushService] from inserted i;
select @Status=i.[Status] from inserted i;
INSERT INTO [Messages]
(RequestID,AssignedToUser,[TimeStamp],[Hour],RushService,[Status],MessageText) VALUES (@Id,@AssignedToUser,GETDATE(),@Hour,@RushService,@Status,'New Critical Request')
END
Run Code Online (Sandbox Code Playgroud)
这工作正常,除了我需要修改它,这样它只在“AssignedToUser”列值实际更改为新值时触发对“Messages”表的插入。如果更新行时“AssignedToUser”的值保持不变,则不应触发触发器。提前感谢朋友们...
假设您有一个主键Users,这并不困难。让我假设主键是RequestId.
然后:
insert into messages( . . . )
select i.id, i.assignedtouser, i.hour, i.rushservice, i.status
from inserted i join
deleted d
on i.requestid = d.requestid
where i.assignedtouser <> d.assignedtouser;
Run Code Online (Sandbox Code Playgroud)
注意:您永远不应该假设这一点inserted并且deleted只有一行,就像您的原始代码那样。update当有人尝试多行时,这只会失败。
您还应该在语句中明确包含列列表insert。所以. . .是表中列的列表messages。
| 归档时间: |
|
| 查看次数: |
6132 次 |
| 最近记录: |