循环遍历数据库中的每个表并删除并创建触发器

时间:2017-06-15 07:05:12

标签: sql-server loops triggers

我有两个执行触发器的语句:

IF EXISTS (SELECT * FROM sys.triggers 
      WHERE Object_ID = Object_ID("Insert_Serverdate_Into_CreatedAt"))
 DROP TRIGGER Insert_Serverdate_Into_CreatedAt
GO

CREATE TRIGGER Insert_Serverdate_Into_CreatedAt ON *myTable*
AFTER INSERT
AS
BEGIN
INSERT INTO *myTable* (CreatedAt) VALUES(GETDATE())
END
GO

IF EXISTS (SELECT * FROM sys.triggers 
      WHERE Object_ID = Object_ID("Insert_Serverdate_Into_UpdatedAt"))
DROP TRIGGER Insert_Serverdate_Into_UpdatedAt
GO

CREATE TRIGGER Insert_Serverdate_Into_UpdatedAt ON *myTable*
AFTER UPDATE
AS
BEGIN
INSERT INTO *myTable* (UpdatedAt) VALUES(GETDATE())
END
GO

现在我发现了两种在数据库中遍历每个表的可能性 第一个是:

EXECUTE sp_MSforeachtable @command1 = myCommand

第二个是:

DECLARE @NAME VARCHAR(100)
DECLARE @SQL NVARCHAR(300)

DECLARE CUR CURSOR FOR
   SELECT NAME
   FROM   SYS.TABLES
   WHERE  TYPE = 'U'
     AND SCHEMA_ID = 1

OPEN CUR

FETCH NEXT FROM CUR INTO @NAME

WHILE @@FETCH_STATUS = 0
 BEGIN
  SET @SQL = myCommand

  PRINT @SQL
  EXEC Sp_executesql
    @SQL

  FETCH NEXT FROM CUR INTO @NAME
END

CLOSE CUR

DEALLOCATE CUR 

这里的问题是这些可能性不知道执行命令所需的关键字GO。 是否有可能遍历所有表并执行我的声明?

谢谢!

1 个答案:

答案 0 :(得分:1)

为这四个部分中的每一部分提供如此自己的查询:

DECLARE @NAME VARCHAR(100)
DECLARE @SQL1 NVARCHAR(300)
DECLARE @SQL2 NVARCHAR(300)
DECLARE @SQL3 NVARCHAR(300)
DECLARE @SQL4 NVARCHAR(300)

DECLARE CUR CURSOR FOR
   SELECT NAME
   FROM   SYS.TABLES
   WHERE  TYPE = 'U'
     AND SCHEMA_ID = 1

OPEN CUR

FETCH NEXT FROM CUR INTO @NAME

WHILE @@FETCH_STATUS = 0
 BEGIN
  SET @SQL1 = 'IF EXISTS (SELECT * 
                        FROM sys.triggers 
                        WHERE Object_ID = Object_ID(''['+@Name+'_Insert_Serverdate_Into_CreatedAt]'')) 
                 DROP TRIGGER ['+@name+'_Insert_Serverdate_Into_CreatedAt]'
  SET @SQL2 = 'CREATE TRIGGER ['+ @Name + '_Insert_Serverdate_Into_CreatedAt] ON ['+@Name+']
                AFTER INSERT
                AS
                BEGIN
                INSERT INTO ['+@Name+'] (CreatedAt) VALUES(GETDATE())
                END'
  SET @SQL3 = 'IF EXISTS (SELECT * 
                        FROM sys.triggers 
                        WHERE Object_ID = Object_ID(''['+@Name+'_Insert_Serverdate_Into_UpdatedAt]''))
                    DROP TRIGGER ['+@name+'_Insert_Serverdate_Into_UpdatedAt]'
  SET @SQL4 = 'CREATE TRIGGER ['+@Name+'_Insert_Serverdate_Into_UpdatedAt] ON ['+@Name+']
                AFTER UPDATE
                AS
                BEGIN
                INSERT INTO ['+ @Name+'] (UpdatedAt) VALUES(GETDATE())
                END'

  PRINT @SQL1
  EXEC Sp_executesql @SQL1
  PRINT @SQL2
  EXEC Sp_executesql @SQL2
  PRINT @SQL3
  EXEC Sp_executesql @SQL3
  PRINT @SQL4   
  EXEC Sp_executesql @SQL4

  FETCH NEXT FROM CUR INTO @NAME
END

CLOSE CUR

DEALLOCATE CUR