Question

I'm having issues with a dynamic SQL script in particular this bit:EXEC('

if db_id(''' + $(db) + ''') is null
BEGIN
    CREATE DATABASE ' + $(db) + '
END

The if statement part seems to work fine, I know this because if the database exists then the create database line is not run but when it needs to run I just get syntax errors near that line.

I have also tried:

CREATE DATABASE ''' + $(db) + '''

with no luck

Any Ideas?

Was it helpful?

Solution

DECLARE @DB_NAME NVARCHAR(128) = N'Test_DB'
DECLARE @Sql NVARCHAR(MAX);

IF DB_ID(@DB_NAME) IS NULL
BEGIN
   SET @Sql = N' CREATE DATABASE ' + QUOTENAME(@DB_NAME)

   EXECUTE sp_executesql @Sql
END

Important Note

Make sure your database name is in accordance with the Rules for Regular Identifiers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top