5

I would like create a database using value from a variable. Here my script but it does not work. Any ideas?

-- Set Data Base name
DECLARE @DataBaseName char(64);
SET @DataBaseName = 'DbCmsWebsiteTest';

-- Create Data Base
CREATE DATABASE @DataBaseName;
GO
2
  • Of course the need to dynamically create a database is usually the sign of a database design flaw. Commented Aug 3, 2010 at 18:58
  • 1
    Not if it's used for debugging and local testing, where you want to create multiple dbs for testing purposes. Commented Jul 16, 2021 at 11:30

2 Answers 2

13

You'd need dynamic SQL for this I think (with appropriate precautions if the name is user supplied)

-- Set Data Base name
DECLARE @DataBaseName sysname;
SET @DataBaseName = 'DbCmsWebsiteTest';

IF (@DataBaseName  LIKE '%[^0-9A-Z]%')
    RAISERROR('Invalid Characters in Name, %s',16,1,@DataBaseName)
ELSE
    BEGIN
    SET @DataBaseName = QUOTENAME(@DataBaseName)
    EXEC('CREATE DATABASE '+ @DataBaseName)
    END
Sign up to request clarification or add additional context in comments.

2 Comments

But I would not check the valid name rules myself, rather let the CREATE raise. For instance, your check rules out many valid characters like space, _, - etc.
@Remus - Agreed - I was a bit ambivalent about SQL injection possibilities but I guess QUOTENAME would deal with that anyway.
2

Actually, the recommended approach is the sp_executesql function.

Here's an example of using it:

DECLARE @SqlCommand NVARCHAR(255), @DatabaseName NVARCHAR(63)
SET @DatabaseName = 'DbName'
SET @SqlCommand = N'CREATE DATABASE ' + @DatabaseName
EXECUTE sp_executesql @SqlCommand

3 Comments

Gives Incorrect syntax near '@DatabaseName'. You'd need to find some syntax that accepts a parameter for the database name (in which case you wouldn't need dynamic SQL anyway you could just call it directly)
In addition to Martin's comment, sp_executesql is SQL Server 2005+ syntax, and ATM we're not aware of what version of SQL Server this is for...
Got it! I did kinda hurry there :) My idea with sp_executesql was based on the fact that msdn recommends using it when possible. But since its main advantage is when it comes to the execution plans, I guess it's not that important which option is used in this case.

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.