近日在做内部的一个项目时,用到了触发器,将部分代码贴出来,以供参考。
-- =============================================
-- Author: QW
-- Create date: 2011-5-5
-- Description: 项目信息表触发器,添加时触发
-- =============================================
ALTER TRIGGER [dbo].[TRIGGER_INSERT_PROJECT_INFO]
ON [dbo].[project_info]
AFTER INSERT
AS
declare @interval_day int,@oper_cond varchar(10)
declare @pStartTime datetime,@pEndTime datetime,@Id int,@pType int,@pTypeChild int,@pTypeChildZhuanye int
--检验游标cur_insert的存在性,如果存在就删除
if cursor_status('global', 'cur_insert') <> -3
or cursor_status('local', 'cur_insert') <> -3
begin
deallocate cur_insert
end
--添加时触发
if exists(select 1 from inserted)
begin
declare cur_insert cursor local for
select Id,pName,pStartTime,pEndTime,pType,pTypeChild,pTypeChildZhuanye,pCreateUser from inserted
open cur_insert --打开游标
fetch next from cur_insert into @Id,@pName,@pStartTime,@pEndTime,@pType,@pTypeChild,@pTypeChildZhuanye,@pCreateUser
while @@fetch_status = 0
begin
if not exists(select * from exc_projrun_t where ProjectID=@Id)
BEGIN
insert into exc_projrun_t(ProjectID,OperatingCondition,NodeName,PreviousNode,ProjectState,UpdateTime)
values(@Id,@oper_cond,'登记审核','项目登记','运行中',Current_Timestamp);
END
--下一行
fetch next from cur_insert into @Id,@pName,@pStartTime,@pEndTime,@pType,@pTypeChild,@pTypeChildZhuanye,@pCreateUser
end
close cur_insert
deallocate cur_insert
end