为什么你需要一次跑步?这是唯一的方法。
Msg 111, Level 15, State 1, Line 2
'CREATE TRIGGER' must be the first statement in a query batch.
运行由此生成的输出:
DECLARE @DatabaseName varchar(500)
DECLARE @Database_id int
DECLARE @Query varchar(8000)
DECLARE @CRLF char(2)
SET @CRLF=CHAR(13)+CHAR(10)
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
select @Database_id=MIN(database_id) from sys.databases where database_id IN (5,7,8,6)
WHILE @Database_id IS NOT NULL
BEGIN
SELECT @DatabaseName=name from sys.databases where database_id=@Database_id
SET @Query='-- Create table'+@CRLF+@CRLF
+'use '+@DatabaseName+@CRLF
+' GO'+@CRLF
+' CREATE TABLE dbo.ChangeAttempt'+@CRLF
+' (EventData xml NOT NULL,'+@CRLF
+' AttemptDate datetime NOT NULL DEFAULT GETDATE(),'+@CRLF
+' DBUser char(50) NOT NULL)'+@CRLF
+'GO'+@CRLF+@CRLF
+'-- Create DDL trigger '+@CRLF+@CRLF
+'use '+@DatabaseName+@CRLF
+'GO'+@CRLF
+'CREATE TRIGGER db_trg_ObjectChanges'+@CRLF
+'ON DATABASE'+@CRLF
+'FOR ALTER_PROCEDURE, DROP_PROCEDURE,'+@CRLF
+' ALTER_INDEX, DROP_INDEX,'+@CRLF
+' ALTER_TABLE, DROP_TABLE, ALTER_TRIGGER, DROP_TRIGGER,'+@CRLF
+' ALTER_VIEW, DROP_VIEW, ALTER_SCHEMA, DROP_SCHEMA,'+@CRLF
+' ALTER_ROLE, DROP_ROLE, ALTER_USER, DROP_USER'+@CRLF
+'AS'+@CRLF
+'SET NOCOUNT ON'+@CRLF
+'INSERT dbo.ChangeAttempt'+@CRLF
+'(EventData, DBUser)'+@CRLF
+'VALUES (EVENTDATA(), USER)'+@CRLF
+'GO'+@CRLF
PRINT @Query
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
select @Database_id=MIN(database_id) from sys.databases WHERE database_id IN (5,7,8,6) AND database_id>@Database_id
END
编辑
以确定要为其生成脚本的数据库执行以下操作:
运行此查询:
从 sys.databases 中选择 database_id,name
找到要为其运行脚本的所有数据库
在两个地方(循环之前和循环底部)更改我上面的脚本,因此您想要的所有 database_id 都在以下代码部分中:
WHERE database_id IN (AAA,BBB,CCC,DDD,....)