How to use SqlCommand to CREATE DATABASE with parameterized db name?

Sadly you can accomplish this by wrapping your DDL operation in a DML operation.

var createDatabaseQuery = "exec ('CREATE DATABASE ' + @databaseName)";

var sqlCommand = new SqlCommand(createDatabaseQuery, sqlConnection);
sqlCommand.Parameters.Add("@databaseName", SqlDbType.Text);
sqlCommand.Parameters["@databaseName"].Value = "HelloWorld";

sqlCommand.ExecuteNonQuery();

You can only use parameters in places where SQL Server supports them. Unfortunately SQL Server does not support parameterised CREATE DATABASE statements (although I have a feeling the filename parts may support parameters).

You'll need to construct the SQL yourself:

string dataBaseAttachText = "CREATE DATABASE [" + dbName + "] " + 
                              "ON (FILENAME = @filename) " + 
                              "LOG ON (FILENAME = @filenamelog) " + 
                              "FOR ATTACH GO"; 
var cmd = CreateCommand(dataBaseAttachText); 

SetParameter(cmd, "@filename", @"c:\demo_data.mdf"); 
SetParameter(cmd, "@filenamelog", @"c:\demo_data.mdf.LDF"); 

cmd.ExecuteNonQuery(); 

CAUTION: this is susceptable to SQL-injection attacks so caremust be taken; if you don't trust the source of the database name, don't do this!

You'll need to make similar changes to the filename parts if those can't be parameterised either.


Parameters are supported for DML operations not DDL operations, there are no execution plans for DDL operations. you will need to use dynamic SQL

DDL = Data Definition Language (create, drop, alter....)

DML = Data Manipulation Language (select, update, delete, insert)