Incorrect Syntax Near GO, T-SQL EXEC()

你离开我真会死。 提交于 2019-12-02 01:12:11

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.

You can use following script for solution to your requirement with the help of unsupported undocumented stored procedure sp_MSForEachDB

EXEC sp_MSForEachDB '
Use [?]; 
IF ''[?]'' = ''[ABC]'' 
begin
    -- Create Schema
    exec sp_executesql N''CREATE SCHEMA meta''
end
'
EXEC sp_MSForEachDB '
Use [?]; 
IF ''[?]'' = ''[ABC]'' 
begin 
    -- Create Log Table
    CREATE TABLE meta.LogAudit(
    [EventDate] [datetime] NOT NULL DEFAULT (getdate()),
    [EventType] [nvarchar](64) NULL,
    )
end'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!