0

Does anyone know why the first code works but the second does not? At the second I get exception (wrong syntax near @databaseName).

First Code

public void CreateDatabase(string databaseName)
{
     string command = "CREATE DATABASE " + databaseName;
     using (SqlConnection sqlConn = new SqlConnection(_sqlConnectionStringBuilder.ToString()))
     {
          sqlConn.Open();
          using (SqlCommand sqlComm = new SqlCommand(command, sqlConn))
          {
               sqlComm.ExecuteNonQuery()
          }
     }
}

Second Code

public void CreateDatabase(string databaseName)
{
     string command = "CREATE DATABASE @databaseName";   \\I tried both
     string command = "CREATE DATABASE '@databaseName'";  \\I tried both
     using (SqlConnection sqlConn = new SqlConnection(_sqlConnectionStringBuilder.ToString()))
     {
          sqlConn.Open();
          using (SqlCommand sqlComm = new SqlCommand(command, sqlConn))
          {
               sqlComm.Parameters.Add(new SqlParameter(@"databaseName", databaseName));
               sqlComm.ExecuteNonQuery()
          }
     }
}
4
  • 1
    Because you can't use a parameter for a ddl statement. Why do you need to create a database in your application anyway? Commented May 4, 2018 at 18:10
  • thank you. because I am currently learning MVVM and would like to write a sample program Commented May 4, 2018 at 18:13
  • Possible duplicate of SQL Server: How to use a database name as a parameter in a stored procedure? Commented May 4, 2018 at 18:24
  • Not sure why that requires you to constantly need more databases but I will just pass that as a different discussion. Commented May 4, 2018 at 18:47

1 Answer 1

1

In TSQL the general rule is you can't parameterize Data Definition Language (DDL) statements at all. And you can't use parameters in place of identifiers in Data Manipulation Language (DML) statements.

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.