SQL Server 触发器(表数据添加)

本文介绍了一个具体的SQL触发器实现案例,用于在项目信息表中添加记录时触发相应操作。通过游标遍历新增数据,并在exc_projrun_t表中插入记录以记录项目的运行状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近日在做内部的一个项目时,用到了触发器,将部分代码贴出来,以供参考。
-- =============================================
-- 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值