0

I have a code to create database with dapper:

public static bool CreateDatabase(string connectionString, string databaseName)
{
    const string DATABASE_CREATE_QUERY = "CREATE DATABASE (@databaseName)";

    using (var connection = new SqlConnection(connectionString))
    {
        var affectedRows = connection.Execute(DATABASE_CREATE_QUERY, new { databaseName });

        return affectedRows > 0 ? true : false;
    }
}

CreateDatabase("Server=10.10.10.10;User ID=user;Password=password;MultipleActiveResultSets=true;", "TEST_DB");

Every time I run this method, I get an error:

Incorrect syntax near '('.

With trace:

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) in E:\GitHub\Dapper\Dapper\SqlMapper.cs:line 2827
at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) in E:\GitHub\Dapper\Dapper\SqlMapper.cs:line 570
at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in E:\GitHub\Dapper\Dapper\SqlMapper.cs:line 443
at DbCreator.DbUtils.CreateDatabase(String connectionString, String databaseName) in E:\src_projects\DbCreator\DbUtils.cs:line 48
at DbCreator.***.Run(String connectionString) in E:\src_projects\DbCreator\***.cs:line 23

If I set the query the ugly way

const string DATABASE_CREATE_QUERY = $"CREATE DATABASE {databaseName}";

and run

connection.Execute(DATABASE_CREATE_QUERY);

it all works fine.

If I don't use the brackets () in the QUERY

const string DATABASE_CREATE_QUERY = "CREATE DATABASE @databaseName";

I get an error:

Incorrect syntax near '@databaseName'

I have also tried methods ExecuteScalar, Query, but with the same result.

Any ideas why this wont work the Dapper way?

vidriduch
  • 4,753
  • 8
  • 41
  • 63
  • 1
    I'd be tempted to log an issue on the [Github page](https://github.com/StackExchange/Dapper/issues) – Liam Oct 04 '18 at 13:43

2 Answers2

5

This is because sp_executesql is being used for parameterizing.This is what is being executed in the database via Dapper interpretation;

exec sp_executesql N'Create Database (@DBName)',N'@DBName nvarchar(4000)',@DBName=N'Test'

See why that wont work with sp_executesql: Table name as variable

Your best bet would be to either create a stored procedure, or use the approach of string replacement.

Hozikimaru
  • 1,144
  • 1
  • 9
  • 20
-2

Because create database statement doesn't require ().

Try :

const string DATABASE_CREATE_QUERY = "CREATE DATABASE @databaseName";
DanB
  • 2,022
  • 1
  • 12
  • 24