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:
- Can you pass a parameter to define the table list in the FROM statement?
- If you can, why isn't this working?