Giving error while creating schema

  • Hi all,

    I am using the following script for creating the schema

    USE [TEMP]

    IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'lsrSchema')

    begin

    select 'Test print'

    CREATE SCHEMA [lsrSchema] AUTHORIZATION [lsr]

    end

    if we run "CREATE SCHEMA [lsrSchema] AUTHORIZATION [lsr]" without the condition it works fine and created the schema. But when try to execute the abouve script its giving the following error

    Msg 156, Level 15, State 1, Line 7

    Incorrect syntax near the keyword 'SCHEMA'.

    its giving error even though the control is not going inside the begin -end section while execution

    Please help me out to resolve this

  • try it by using below script..

    USE [TEMP]

    GO

    IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = N'lsrSchema')

    BEGIN

    PRINT 'test Print'

    CREATE SCHEMA [lsrSchema] AUTHORIZATION [lsr]

    END

    GO

  • Check BOL... it tells you that CREATE SCHEMA must be run in its own batch.

    Therefore you aren't going to be able to put any other statements (e.g. if exists...) in the same batch.

  • Hi,

    I am using the following script

    set @Query='

    USE ['+@DatabaseName+']

    IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'''+@SchemaName+''')

    CREATE SCHEMA ['+@SchemaName+'] AUTHORIZATION ['+@UserName+']

    '

    exec (@Query)

    While executing its giving error "Incorrect syntax near the keyword 'SCHEMA". ..Please help me out to resolve this...

    Thanks,

    Aneesh

  • Hi,

    'create schema' must the be the first line in a batch. here is the

    workaround.

    USE [TEMP]

    IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'lsrSchema')

    begin

    select 'Test print'

    exec('CREATE SCHEMA [lsrSchema] AUTHORIZATION [lsr]')

    end

    try this

  • USE [SampleDB]

    IF ((SELECT COUNT(*) FROM sys.schemas WHERE name = N'sampleSchema') = 0)

    BEGIN

    exec('CREATE SCHEMA [sampleSchema] AUTHORIZATION [dbo]')

    PRINT 'Schema Exists'

    END

    GO

    - Serves our purpose

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply