Search code examples
c#sqlparameters

Can you use a SQLParameter in the SQL FROM statement?


I am trying to create a parameterized query in C# against a SQL server database.

Code:

query = new StringBuilder( "SELECT @fields FROM @tables");

using(SqlConnection connection = new SqlConnection(connection))
{
    SqlCommand command = new SqlCommand(query.ToString(), connection);
    command.Parameters.AddWithValue("@fields", fields.ToString());
    command.Parameters.AddWithValue("@tables", tables.ToString());

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

The strange part is this fails with the message "Must declare the table variable "@tables". However as you can see, it's clearly been defined.

So my question is:

  1. Can you pass a parameter to define the table list in the FROM statement?
  2. If you can, why isn't this working?

Solution

  • SQL doesn't support the FROM clause to be parameterized. So you have to use either dynamic SQL, or create/concatenate the query string prior to submitting it to the database.