Why do I receive an incorrect syntax error when try to parameterize a table name?

I have the following code:

string strTruncateTable = "TRUNCATE TABLE @TableNameTruncate";
SqlCommand truncateTable = new SqlCommand(strTruncateTable, myConnection);              
truncateTable.Parameters.AddWithValue("TableNameTruncate", tbTableName.Text);
truncateTable.ExecuteNonQuery();

Whenever I run the application, I get the following error:

Incorrect syntax near '@TableNameTruncate'

How can I fix the issue?

Jon Skeet
people
quotationmark

How can I fix the issue?

By specifying the table name as part of the SQL. Table and column names can't be parameterized in most database SQL dialects, including SQL Server.

You should either perform very stringent validation on the table name before putting it into the SQL, or have a whitelisted set of valid table names, in order to avoid SQL injection attacks in the normal way.

people

See more on this question at Stackoverflow