简体   繁体   中英

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?

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.

You can only parameterized your values , not your column names or table names no matter you use DML statements or DDL statements.

And by the way, parameters are supported for Data manipulation language operations not Data Manipulation language operations.

Data manipulation language =

SELECT ... FROM ... WHERE ...
INSERT INTO ... VALUES ...
UPDATE ... SET ... WHERE ...
DELETE FROM ... WHERE ...

TRUNCATE TABLE is a Data Definition Language statement . That's why you can't use TRUNCATE TABLE with parameters even only if you try to parameter a value . You need to specify it as a part of SQL query.

You might need to take a look at the term called Dynamic SQL

As mentioned by Jon Skeet, table name cannot be parametrized for truncate operation.

To fix this issue, fully qualified query needed to be written.

So you can put a conditional check by the parameter value @TableNameTruncate and using if or switch case statement create fully qualified query then execute it.

or simply

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM