Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to add some stuff (tables, stored procedures, etc.) to an existing sqlserver 2005 database. To avoid potential name conflicts I want to put them all in my own schema. But I am running into a problem. I am using SQL Server Management Studio to run the following code.

SQL
USE AdventureWorks
GO

CREATE SCHEMA [pja]
GO

SELECT * FROM sys.schemas
GO
This works great as the schema is created and I can use it. But it produces an error if the schema is already present:
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'pja' in the database.
Msg 2759, Level 16, State 0, Line 2
CREATE SCHEMA failed due to previous errors.

I want to avoid the error so I wanted to check for the existance of the schema before I call CREATE SCHEMA:
SQL
USE AdventureWorks
GO

IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'pja')
BEGIN
    PRINT '--- Creating schema "pja"'
    CREATE SCHEMA [pja]
END
GO

SELECT * FROM sys.schemas
GO
The schema is not created and the error message is now:
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'SCHEMA'.

What is the proper way to attempt to create a schema only if it does not already exist?
Posted

1 solution

Ran into this not too long ago and found this solution:
Schema Workaround[^]

Hope this helps.

Cheers.
 
Share this answer
 
Comments
PJ Arends 17-Nov-10 17:28pm    
Thanks, works now. Kind of a weird solution though.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900