0

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?

6
  • 1
    Why you have a dollar sign in your DB name? in your above question you are trying to create a database with name as ' + $(db) + '. This violates the Sql server identifier name rules please read this Rules for Regular Identifiers Commented Apr 17, 2014 at 10:49
  • Its Dynamic Sql and the DB name is passed in, it works perfectly for the if statement just not the create database bit. Commented Apr 17, 2014 at 10:51
  • What ever string I pass in through the command line Commented Apr 17, 2014 at 10:57
  • what do you want your database name to be ? It is working fine for IF statement because if statement doesnt have to create this database it just checks if there is a database with this name or not, On the other hand Create statement checks if the passed name is in compliant with identifier rules and errors out as you proposed name violates that, Please read the link mentioned above in my comment. thank you Commented Apr 17, 2014 at 11:00
  • Ok well the string I am passing in at the moment is Test1 so I don't think I am violating any thing Commented Apr 17, 2014 at 11:04

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.