3

我正在尝试使用SqlParameters. 我有这个代码。

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

我收到此错误:

'@nume' 附近的语法不正确。

但是当我这样做时

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

它有效,我真的不明白这个错误。

4

2 回答 2

4

您不能使用参数作为表名。尽管您通常会在这里被告知使用字符串连接构建查询,但这是您需要的一个场合!

SqlCommand com=new SqlCommand("drop table " + name, dbCon);
于 2015-03-12T19:21:55.317 回答
1

我不推荐它,但如果你真的想使用 SQLParameter,那么这种方式是可能的。

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

但实际上,这样做并没有任何优势。这适用于 SQL Server 2005 及其最新版本。

于 2015-03-12T19:36:36.753 回答