How do I query if a database schema exists

前端 未结 5 629
野性不改
野性不改 2020-12-25 09:19

As part of our build process we run a database update script as we deploy code to 4 different environments. Further, since the same query will get added to until we drop a r

5条回答
  •  遥遥无期
    2020-12-25 09:51

    This is old so I feel compelled to add: For SQL SERVER 2008+ These all work (for the select part), then use EXECUTE('CREATE SCHEMA ') to actually create it on negative results.

    DECLARE @schemaName sysname = 'myfunschema';
    -- shortest
    If EXISTS (SELECT 1 WHERE SCHEMA_ID(@schemaName) IS NOT NULL)
    PRINT 'YEA'
    ELSE
    PRINT 'NOPE'
    
    SELECT DB_NAME() AS dbname WHERE SCHEMA_ID(@schemaName) IS NOT NULL -- nothing returned if not there
    
    IF NOT EXISTS ( SELECT  top 1 *
                    FROM    sys.schemas
                    WHERE   name = @schemaName )
    PRINT 'WOOPS MISSING'
    ELSE
    PRINT 'Has Schema'
    
    SELECT SCHEMA_NAME(SCHEMA_ID(@schemaName)) AS SchemaName1 -- null if not there otherwise schema name returned
    
    SELECT SCHEMA_ID(@schemaName) AS SchemaID1-- null if not there otherwise schema id returned
    
    
    IF EXISTS (
        SELECT sd.SchemaExists 
        FROM (
            SELECT 
                CASE 
                    WHEN SCHEMA_ID(@schemaName) IS NULL THEN 0
                    WHEN SCHEMA_ID(@schemaName) IS NOT NULL THEN 1
                    ELSE 0 
                END AS SchemaExists
        ) AS sd
        WHERE sd.SchemaExists = 1
    )
    BEGIN
        SELECT 'Got it';
    END
    ELSE
    BEGIN
        SELECT 'Schema Missing';
    END
    

提交回复
热议问题