Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create schema inside begin block

Tags:

sql

sql-server

I'm completely stumped. I have the following block:

IF NOT EXISTS(SELECT * FROM sys.schemas WHERE name = 'Test')
BEGIN
    CREATE SCHEMA Test;
END;

If I run this against our SQL Server 2008, I get "Msg 156, Level 15, State 1, Line 3: Incorrect syntax near the keyword 'SCHEMA'" but if I run just the CREATE SCHEMA command alone, it works.

Also, this works:

IF NOT EXISTS(SELECT * FROM sys.schemas WHERE name = 'Test')
BEGIN
    PRINT 'CREATE GOES HERE';
END;

What am I doing wrong?

like image 768
mzedeler Avatar asked Sep 09 '13 11:09

mzedeler


People also ask

Can we create schema inside schema?

A CREATE command specifying an unqualified object name creates the object in the current schema (the one at the front of the search path, which can be determined with the function current_schema ). Optionally, CREATE SCHEMA can include subcommands to create objects within the new schema.

How do I create a new schema?

To create a schema In Object Explorer, expand the Databases folder. Expand the database in which to create the new database schema. Right-click the Security folder, point to New, and select Schema. In the Schema - New dialog box, on the General page, enter a name for the new schema in the Schema name box.


2 Answers

The error message is a bit of a red herring here.... Execute the following to see what the "real" error is:

SELECT * FROM sys.schemas
CREATE SCHEMA Test

Msg 111, Level 15, State 1, Line 2

'CREATE SCHEMA' must be the first statement in a query batch.

To get around this problem you can use the EXEC function:

IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'Test')
  BEGIN
    EXEC ('CREATE SCHEMA Test;');
  END;
like image 110
gvee Avatar answered Sep 20 '22 20:09

gvee


If you need to create schema in another database rather than current context, you should run following script.

set @myScript = 'exec '+ QUOTENAME(@DBName) + '..sp_executesql N''create schema MySchema'''
execute(@myScript)
like image 37
Will Wu Avatar answered Sep 19 '22 20:09

Will Wu