Incorrect Syntax Near GO, T-SQL EXEC()

前端 未结 2 460
鱼传尺愫
鱼传尺愫 2021-01-21 23:45

I am using the following script:

DECLARE @dbName NVARCHAR(20) = \'ABC\';
EXEC ( N\' USE \' + @dbName + \'
GO

-- Create Schema
CREATE SCHEMA meta
GO

-- Create L         


        
2条回答
  •  时光说笑
    2021-01-22 00:13

    Try removing comma after [EventType] [nvarchar](64) NULL, and see if the error message changes.

    So you have 2 problems:

    1. As @Tanner has pointed out, you cannot use GO in dynamic SQL.
    2. You still have that trailing comma in the meta.LogAudit table columns definition.

    Try running this code:

    DECLARE @dbName NVARCHAR(20) = 'ABC';
    declare @sql nvarchar(max) = N'exec '+ @DBName + '..sp_executesql N''CREATE SCHEMA meta'''
    execute(@sql)
    declare @sql2 nvarchar(max) = '
    -- Create Log Table
    CREATE TABLE '+ @DBName + '.meta.LogAudit(
    [EventDate] [datetime] NOT NULL DEFAULT (getdate()),
    [EventType] [nvarchar](64) NULL
    )'
    exec sp_executesql @sql2,N''
    

    It will allow you to programmatically create schema in the specified Database as opposite to using current database.

提交回复
热议问题