SQL Server:带有SQL参数的drop table

时间:2022-10-09 03:37:36

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

我正在尝试使用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();

I receive this error :

我收到此错误:

Incorrect syntax near '@nume'.

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

But when I do

但是,当我这样做

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

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

它工作,我真的不明白这个错误。

2 个解决方案

#1


3  

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

#2


1  

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

我不推荐它,但如果你真的想使用SQLParameter,那么就有可能这样。

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.

但实际上,这样做没有任何优势。这项工作在SQL Server 2005及其最新版本上。

#1


3  

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

#2


1  

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

我不推荐它,但如果你真的想使用SQLParameter,那么就有可能这样。

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.

但实际上,这样做没有任何优势。这项工作在SQL Server 2005及其最新版本上。