简体   繁体   中英

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.

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);

I do not recommand it, but if you really want to use SQLParameter, then it is possible this way.

SqlCommand com=new SqlCommand("EXEC('drop table ''' + @nume + '''')", dbCon);

But really, there is no advantage in doing it this way. This work on SQL Server 2005 and newest version of it.

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