Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use "create schema" in a begin/end block in SQL Management Studio?

I generated a script which creates all users and schemas for this database and when I wrap the CREATE statements with an IF EXISTS check I find that it does not allow the CREATE SCHEMA call to run in the BEGIN/END block. It complains that it is invalid syntax. Yet I can run the command on it's own. A sample of the code is below. I am using SQL Server 2008 and Management Studio R2. Why is this invalid syntax?

--DROP SCHEMA [acme]  IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'acme'))  BEGIN     CREATE SCHEMA [acme] AUTHORIZATION [dbo] END 
like image 543
Brennan Avatar asked Apr 21 '11 18:04

Brennan


People also ask

How do I create a schema in SQL Server Management Studio?

Using SQL Server Management StudioRight-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. In the Schema owner box, enter the name of a database user or role to own the schema.

How do I create a staging schema in SQL Server?

Creating a new SCHEMA in databaseGo to Database > expand Security Folder > Next, expand Schemas Folder there you will see a schema newly created schema Staging. Using SQL Query: Following Statement returns all the list of available schema in database Prod_Db. You can see, Staging schema is also there in result.

How do I create a database schema in MySQL?

Steps to create a schema in MySQLOpen the MySQL Workbench. Click the Create Schema option. Provide a schema name. Click apply to create the MySQL scheme.


1 Answers

Schema creations must be the only statement in a batch. One way to get around it is like so:

IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'acme'))  BEGIN     EXEC ('CREATE SCHEMA [acme] AUTHORIZATION [dbo]') END 
like image 130
Tom H Avatar answered Sep 22 '22 08:09

Tom H