3

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3052078
  • 487
  • 1
  • 8
  • 20

2 Answers2

4

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);
Richard
  • 29,854
  • 11
  • 77
  • 120
1

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.

AXMIM
  • 2,424
  • 1
  • 20
  • 38