为此我专门写了两个存储过程,适用于sql server 2000,如果您的数据库不是sql server 2000,也可供您参考 为了新建立的表和触发器和数据库中原有的表和触发器同名,采用了加后缀方法,比如 表名为 users的表,相应的更新表为users+后缀,当后缀为_1234567时,更新表的表名为users_1234567
create procedure p_analysis @postfix char(8) as --测试是否会和数据库原有的对象名(字段名)重复 if exists(select * from sysobjects where right(name,8)[email protected]) or exists(select * from syscolumns where
right(name,8)[email protected]) print '对象名重复,请使用不同的后缀民名' else begin --为每个表建立更新记录表 declare @tablename nvarchar(128) declare @columns varchar(8000) declare cur insensitive cursor for select name from sysobjects where xtype='u' and status>0 open cur fetch next from cur into @tablename while(@@fetch_status=0) begin set @columns='' --建立更新表 exec('select * into '[email protected][email protected]+' from '[email protected]+' where 1=0') --为更新表增加三个字段 exec('alter table '[email protected][email protected] + ' add id'[email protected]+' int identity(1,1),oprtype'[email protected]+'
char(2),oprtime'[email protected]+' datetime default getdate()') --为每个业务表建立三个触发器 select @[email protected]+','+name from syscolumns where id=object_id(@tablename)
fetch next from cur into @tablename end close cur deallocate cur --建立总记录更新表 exec('create table update'[email protected][email protected]+'(id numeric(18,0) identity(1,1),tablename varchar(256),oprtype
char(1),oprtime datetime default getdate())') end go
exec('if exists (select * from sysobjects where name =''update'[email protected][email protected]+''' and type=''u'')'+ 'drop table update'[email protected][email protected]) declare @tablename nvarchar(128) declare cur cursor for select name from sysobjects where xtype='u' and status>0 open cur fetch next from cur into @tablename while(@@fetch_status=0) begin --删除更新表 exec('if exists (select * from sysobjects where name ='''[email protected][email protected]+''' and type=''u'')'+ 'drop table '[email protected][email protected]) --删除插入触发器 exec('if exists (select * from sysobjects where name =''tr_'[email protected]+'_i'[email protected]+''' and type=''tr'')'+ 'drop trigger tr_'[email protected]+'_i'[email protected]) --删除删除触发器 exec('if exists (select * from sysobjects where name =''tr_'[email protected]+'_d'[email protected]+''' and type=''tr'')'+ 'drop trigger tr_'[email protected]+'_d'[email protected]) --删除更新触发器 exec('if exists (select * from sysobjects where name =''tr_'[email protected]+'_u'[email protected]+''' and type=''tr'')'+ 'drop trigger tr_'[email protected]+'_u'[email protected]) fetch next from cur into @tablename end close cur deallocate cur go