I am using the following script:
DECLARE @dbName NVARCHAR(20) = 'ABC';
EXEC ( N' USE ' + @dbName + '
GO
-- Create Schema
CREATE SCHEMA meta
GO
-- Create Log Table
CREATE TABLE meta.LogAudit(
[EventDate] [datetime] NOT NULL DEFAULT (getdate()),
[EventType] [nvarchar](64) NULL
)
GO
'
);
but it throws me the following error.
Msg 111, Level 15, State 1, Line 5
'CREATE SCHEMA' must be the first statement in a query batch.
Msg 102, Level 15, State 1, Line 22
Incorrect syntax near 'GO'.
Why is that?
--
Edit:
This answer seems to be answering my question:
dynamic sql error: 'CREATE TRIGGER' must be the first statement in a query batch
So it seems that in my situation I cannot program it dynamically. My whole code works in the following way:
USE DB
GO
CREATE SCHEMA SCH
GO
CREATE TABLE SCH.TABLE
GO
CREATE TRIGGER TRG
GO
So as SCHEMA
and TRIGGER
needs to be first query statement, it cannot be written in this way.
Try removing comma after
[EventType] [nvarchar](64) NULL,
and see if the error message changes.So you have 2 problems:
meta.LogAudit
table columns definition.Try running this code:
It will allow you to programmatically create schema in the specified Database as opposite to using current database.