views:

64

answers:

2

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
+6  A: 

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
Martin Smith
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 Rusanu
@Remus - Agreed - I was a bit ambivalent about SQL injection possibilities but I guess QUOTENAME would deal with that anyway.
Martin Smith
+1  A: 

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
Corina
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)
Martin Smith
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...
OMG Ponies
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.
Corina