SQL Triggers 触发器
SQL Triggers
这是个好东西,当某个表格某个字段更新,删除,增加时候,如果需要关联表格字段一起处理时,触发器就相当有用了。很久之前,前后端不区分的时候,当表格结构越来越复杂时候,对数据的操作,都要写不少的 .Net 代码来同步更新,后来发现了这个好动西,可以少写很多代码!
Sample:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[trigger_polist_updated]
on [dbo].[POList]
FOR INSERT, Update
AS
begin
declare @article_rows_updated int
-- Should use @@rowcount below but there is a bug because of which sometimes in the presence of
-- other triggers on the table, the @@rowcount cannot be relied on.
select @article_rows_updated = count(*) from inserted
if @article_rows_updated=0
return
UPDATE POlist SET updtime=SYSDATETIME() WHERE UID IN (SELECT DISTINCT UID FROM inserted)
end