使用单个脚本动态执行多个DDL语句?

问题描述 投票:0回答:1

我想在同一个脚本中动态创建多个触发器,但是失败了,你知道有什么方法可以实现这一点吗?

尝试以下脚本:

declare @commands varchar(max) = '
    drop table if exists dbo.Countries
    drop table if exists dbo.Cities

    create table dbo.Countries(
        id int identity not null primary key,
        Country varchar(50) not null
    )

    create table dbo.Cities(
        id int identity not null primary key,
        City varchar(50) not null
    )
'

/* This execution works well */
execute (@commands)
go

declare @commands varchar(max) = '
    create trigger tr_Countries on
        dbo.Countries for insert as
    begin
        print ''A new country was created.''
    end

    create trigger tr_Cities on
        dbo.Cities for insert as
    begin
        print ''A new city was created.''
    end
'
/* This execution fails:
Msg 156, Level 15, State 1, Procedure tr_Countries, Line 8 [Batch Start Line 20]
Incorrect syntax near the keyword 'trigger'. 
*/
execute (@commands)

如您所见,两个批次非常相似,但第一个批次运行成功,但第二个批次失败。

sql-server t-sql dynamic-sql
1个回答
0
投票

我发表了评论,但给了你例子。这段代码将运行 不要用“GO”分隔脚本

declare @commands varchar(max) = '
    drop table if exists dbo.Countries
    drop table if exists dbo.Cities

    create table dbo.Countries(
        id int identity not null primary key,
        Country varchar(50) not null
    )

    create table dbo.Cities(
        id int identity not null primary key,
        City varchar(50) not null
    )'
execute (@commands);

SET @commands = 'CREATE TRIGGER tr_Countries on dbo.Countries for insert as
    begin
        print ''A new country was created.''
    end
'
execute (@commands)

set @commands = 'create trigger tr_Cities on dbo.Cities for insert as
    begin
        print ''A new city was created.''
    end
'
execute (@commands)

© www.soinside.com 2019 - 2024. All rights reserved.