Why table params aren’t allowed in SQL Server? Is there any solution to this?
Example:
using (SqlCommand myCommand = new SqlCommand("SELECT * FROM @table WHERE USERNAME=@username AND PASSWORD=HASHBYTES('SHA1',
@password)", myConnection))
{
myCommand.Parameters.AddWithValue("@table", table);
myCommand.Parameters.AddWithValue("@username", user);
myCommand.Parameters.AddWithValue("@password", pass);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader())
...................
}
Thanks.
You can’t paramaterise that part of the SQL. The server needs to know the name of the table to be able to ‘prepare’ the query, which is done before the parameters are processed.
You might dynamically generate the query, but that may open you up to SQL injection attacks and run-time SQL syntax errors. Also, there is a saving to be had if an SQL statement can be cached by the server – you’ll loose that if every query is dynamically generated.