Home > Database > Mysql Tutorial > SQLServer中对所有的用户表生成触发器

SQLServer中对所有的用户表生成触发器

WBOY
Release: 2016-06-07 15:15:06
Original
1292 people have browsed it

测试的时候比较重要,我们可以知道当前交易影响了哪些表 --用于记录 用户 在当前表上什么时候、做的什么操作:update、insert、delete create table TriggerRecord ( operdt datetime,--触发时间 opertp varchar(10),--操作类型:update、insert、delete ope

测试的时候比较重要,我们可以知道当前交易影响了哪些表

--用于记录用户在当前表上什么时候、做的什么操作:update、insert、delete
create table TriggerRecord
(
 operdt datetime, --触发时间
 opertp varchar(10), --操作类型:update、insert、delete
 opertb varchar(50) --表名
)
--这个表于用保存生成触发器语句,在过程中循环执行
--因为Sqlserver不允许在一个批次同时执行多条create trigger语句
create table T(sqlTrigger varchar(500))
--循环执行存于表中触发器的存储过程
create proc loopExecTrigger
as
begin
 declare @sql varchar(500)
 declare cur cursor for select sqlTrigger from T
 open cur
 fetch cur into @sql
 while @@fetch_status=0
 begin
  execute(@sql)
  fetch cur into @sql
 end
 close cur
 deallocate cur
 delete T
end

--用于生成插入语句的触发器,并将触发器语句保存到表中
select 'insert into T values(''create trigger T_'+name+' on '+name+' for insert as insert into TriggerRecord values(getdate(),''''insert'''','''''+name+''''');'')' from sysobjects where type='U' and name not in('T','TriggerRecord')
--将以上生成的语句拷贝出来执行

--用于生成更新语句的触发器,并将触发器语句保存到表中
select 'insert into T values(''create trigger T_'+name+'_U on '+name+' for update as insert into TriggerRecord values(getdate(),''''update'''','''''+name+''''');'')' from sysobjects where type='U' and name not in('T','TriggerRecord')
--将以上生成的语句拷贝出来执行

--用于生成删除语句的触发器,并将触发器语句保存到表中
select 'insert into T values(''create trigger T_'+name+'_D on '+name+' for delete as insert into TriggerRecord values(getdate(),''''delete'''','''''+name+''''');'')' from sysobjects where type='U' and name not in('T','TriggerRecord')
--将以上生成的语句拷贝出来执行

--执行通过上面语句生成的语句后,再执行存储生成触发器的存储过程
exec loopExecTrigger

--生成删除全部以T开头的触发器的语句
select 'drop trigger '+name+';' from sysobjects where type='TR' and name like 'T_%'

冯立彬的博客



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template