0

I wrote a method to execute SQL commands with parameters. But I get an exception stating there is a syntax error near @p0.

private const string CATALOG_NAME = "test";

ExecuteSqlCommand(@"CREATE DATABASE @p0", CATALOG_NAME);

private void ExecuteSqlCommand(string query, params object[] parameters)
{
    try
    {
        using (var command = new SqlCommand(query, _connection))
        {
            for (int i = 0; i < parameters.Length; i++)
            {
                command.Parameters.Add(new SqlParameter("@p" + i, parameters[i]));
            }
            command.ExecuteNonQuery();
        }
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }
}

I also tried AddWithValue and get the same error. I looked into the command with debugging and everything seems fine.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Thypari
  • 801
  • 1
  • 6
  • 22
  • You **cannot** parametrize database, table, index or column names in T-SQL statements... – marc_s Sep 14 '17 at 13:10
  • Thank you! Unfortunately I got the same error when using a bulk insert.... ExecuteSqlCommand(@"BULK INSERT events FROM @p0 WITH (FIELDTERMINATOR = ',',ROWTERMINATOR = '\n')", csvPath); – Thypari Sep 14 '17 at 13:33
  • That's the same root cause - you **cannot** parametrize these table names, column, file names etc. - you can *only* parametrize **values** in a `WHERE` clause and so forth – marc_s Sep 14 '17 at 13:38
  • Okay. That makes sense. I thought it depends on DDL or DML, so I thought insert should work. – Thypari Sep 14 '17 at 13:45

0 Answers0