SQL: „Create Schema“ nur nach Bedingung…

IF SCHEMA_ID('STG') IS NULL 
BEGIN
CREATE SCHEMA [STG]
END
GO

Das führt zu der Fehlermeldung:

Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'SCHEMA'.

Die Lösung ist:

IF SCHEMA_ID('STG') is NULL 
BEGIN
EXEC sp_executesql N'CREATE SCHEMA [STG]'
END
GO

Auch andere Quelle/Beschreibung:

http://sqldbpros.com/2012/08/sql-create-schema-if-not-exists/

Print Friendly, PDF & Email