我创建触发器的经验有限。这是我最近创建的一个:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[NameTrigger]
ON [dbo].[dbUSNs]
after INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
declare @URNs varchar(100)
declare @Forenames varchar(200)
declare @Surname varchar(100)
declare @Reference int
set @URNs = ''
set @Forenames = ''
set @Surname = ''
set @Reference = 0
declare PersonCursor cursor FOR
select
Replace(Replace(Replace(Forenames,char(39),''),'-',''),' ',''),
Replace(Replace(Replace(Surname,char(39),''),'-',''),' ',''),
Reference,USN from inserted
open PersonCursor
FETCH NEXT FROM PersonCursor INTO @Forenames, @Surname, @Reference, @URNs
WHILE @@FETCH_STATUS = 0
BEGIN
update Person set ForenamesCleansed = @Forenames, SurnameCleansed= @Surname, URNsCleansed=@URNs
where reference = @Reference
FETCH NEXT FROM PersonCursor INTO @Forenames, @Surname, @Reference,@URNs
END
CLOSE PersonCursor
DEALLOCATE PersonCursor
END
我想创建一个触发器,当特定列(称为更新)从0更改为1时触发。这可能吗?
答案 0 :(得分:2)
你正在使用Sql Server:
你有两张特别的表:
INSERTED
和DELETED
。
这些表以这种方式工作:
当您在触发器中应用INSERT
语句时,您会找到完整的表INSERTED
当您在触发器中应用UPDATE
语句时,您会找到完整的表INSERTED
和DELETED
当您在触发器中应用DELETE
语句时,您会找到完整的表DELETED
在INSERTED表中,你会发现所有新值,在DELETED中,你会找到旧值,所以当你编写一个触发器时,你可以检查你的布尔字段的旧值和新值,所以当条件满足您可以应用您想要的其他更改。
答案 1 :(得分:1)
您只需要在光标逻辑中添加IF
:
FETCH NEXT FROM PersonCursor INTO @Forenames, @Surname, @Reference, @URNs
WHILE @@FETCH_STATUS = 0
BEGIN
IF (inserted.[Update] = 0 AND deleted.[Update] = 1) --Added
BEGIN
update Person set ForenamesCleansed = @Forenames, SurnameCleansed= @Surname, URNsCleansed=@URNs
where reference = @Reference
FETCH NEXT FROM PersonCursor INTO @Forenames, @Surname, @Reference,@URNs
END
END
END
您可能想要反转逻辑,问题与其标题之间存在不匹配的变化方向。