Home > OS >  Create Database Dynamically Using C#
Create Database Dynamically Using C#

Time:12-05

I am trying to create a database using this code:

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

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

sqlCommand.ExecuteNonQuery();

The above works perfectly but I try to do concatenation as follows, it throws an exception:

var sqlCommand = new SqlCommand(createDatabaseQuery, sqlConnection);
sqlCommand.Parameters.Add("@db", SqlDbType.Text);
sqlCommand.Parameters["@db"].Value = "DbName"   CustomId; //Doing the concatenation here

Exception:

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '-'

I know, there could be better ways to do it. But is there any way that I can make the above work?

CodePudding user response:

Time to learn the real intricate sides of SQL.

The way you wan t to write it - is incorrect in multiple ways. DEBUG THE SQL. Do not care about the C# code, look at the SQL...

In your case - naming conversions.

Tables, databases etc. can not contains a "-" - OR they must be marked.

CREATE DATABASE my-database -> Error CREATE DATABASE [my-database] -> correct, the [] brackets names and thus... no processing of the "-" is tried.

This is quite clear in the SQL documentation, but a part many people overlook (mostly because in most cases it does not matter). They likely wonder why generators bracket every item name (Database, schema, table, COLUMN). Well, that is the reason. What do you think "-1" means? Minus one, processing, or part of a name - the server has no way to determine this. Help him.

CodePudding user response:

You need to make sure you are quoting the name correctly using QUOTENAME, because it contains characters that need escaping.

var createDatabaseQuery = "exec ('CREATE DATABASE '   QUOTENAME(@db))";

Also, the parameter type should be nvarchar(128)

sqlCommand.Parameters.Add("@db", SqlDbType.NVarChar, 128).Value = "DbName"   CustomId;
  • Related