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?
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.
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.
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;
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With