Create_Schema_if_Missing

Snippet Name: Create_Schema_if_Missing

Tags:

Created Date: 2025-06-16 13:12:47
Last Modified Date: 2025-05-31 10:31:50

Dependencies:

DBA Notes:

Sample Output:

Title: Create Schema if Missing
Author: user
in SQL server,via a TSLq command, and maybe dynamic sql, assume I am in a different user database, but if a schema with my current databasename (using the db_name() function) does not exist in the [DBA_ADMIN] database, i need to create a schema with that name

Author: ChatGPT
You can achieve this by writing a dynamic SQL script that first checks if the schema with the current database name exists in the `[DBA_ADMIN]` database, and if it doesn't exist, it will create the schema.

Here???s an example of how you can implement this:

```sql
DECLARE @schemaName NVARCHAR(128);
DECLARE @sql NVARCHAR(MAX);

-- Get the current database name to use as the schema name
SET @schemaName = DB_NAME();

-- Check if the schema exists in the [DBA_ADMIN] database
IF NOT EXISTS (SELECT * 
               FROM [DBA_ADMIN].sys.schemas 
               WHERE name = @schemaName)
BEGIN
    -- Build the dynamic SQL to create the schema
    SET @sql = N'CREATE SCHEMA [' + @schemaName + N']';
    
    -- Execute the dynamic SQL in the [DBA_ADMIN] database
    EXEC [DBA_ADMIN].sys.sp_executesql @sql;
END
```

### Explanation:
1. `DB_NAME()` retrieves the current database name.
2. The query checks in `[DBA_ADMIN].sys.schemas` to see if a schema with that name already exists.
3. If the schema does not exist, dynamic SQL is generated to create the schema and executed using `sp_executesql` in the `[DBA_ADMIN]` database.

This way, it will create the schema only if it doesn't exist.


Leave a Reply