Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : drop table with SQL parameters

I'm trying to drop a table using SqlParameters. I have this code .

dbCon.Open();
DataRowView d= (DataRowView) cmbTabele.Items[cmbTabele.SelectedIndex];
string name = (d["table_name"]as string);

SqlCommand com=new SqlCommand("drop table @nume ", dbCon);
com.Parameters.Clear();
SqlParameter param = new SqlParameter("@nume", name);
com.Parameters.Add(param);

com.ExecuteNonQuery();   // ERROR HERE
dbCon.Close();

I receive this error :

Incorrect syntax near '@nume'.

But when I do

SqlCommand com = new SqlCommand("drop table " + name, dbCon);

it works, and I really don't understand this error.

like image 450
user3052078 Avatar asked Apr 15 '26 17:04

user3052078


1 Answers

You cannot use a parameter for a table name. Although you'll normally get told off around here for building up a query using string concatenation, this is one occasion where you'll need to!

SqlCommand com=new SqlCommand("drop table " + name, dbCon);
like image 145
Richard Avatar answered Apr 19 '26 09:04

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!