日期:2014-05-17 浏览次数:20565 次
IF EXISTS (SELECT * FROM sys.triggers WHERE parent_class = 0 AND name = 'tt') DROP TRIGGER tt ON DATABASE; GO CREATE TRIGGER tt ON DATABASE FOR CREATE_TABLE AS BEGIN SET CONCAT_NULL_YIELDS_NULL ON DECLARE @AffectedTable nvarchar(255),@backUpTable nvarchar(255),@create_Script nvarchar(max) --获取建表的语句 SELECT @create_Script=EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)') --获取表的名称 SELECT @AffectedTable = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(255)') --定义一个备份的表名称 SELECT @backUpTable =@AffectedTable+'_bk' --替换表名 SELECT @create_Script=REPLACE(@create_Script,@AffectedTable,@backUpTable) --执行建表语句 EXEC(@create_Script) --给创建的表加一个DML触发器 EXEC(' CREATE TRIGGER tt_'+@AffectedTable+' ON '+@AffectedTable+' FOR INSERT AS BEGIN INSERT INTO '+@backUpTable+' SELECT * FROM INSERTED END' ) SET CONCAT_NULL_YIELDS_NULL OFF END --> 测试[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([id] INT,[name] VARCHAR(4)) GO INSERT [tb] SELECT 1,'土豆' UNION ALL SELECT 2,'水锅' SELECT * FROM tb /* id name 1 土豆 2 水锅 */ SELECT * FROM tb_bk /* id name 2 水锅 1 土豆 */ DROP TABLE tb_bk