您可以在SQL FROM语句中使用SQLParameter吗? [英] Can you use a SQLParameter in the SQL FROM statement?
本文介绍了您可以在SQL FROM语句中使用SQLParameter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在C#中针对SQL Server数据库创建参数化查询.
I am trying to create a parameterized query in C# against a SQL server database.
代码:
query = new StringBuilder( "SELECT @fields FROM @tables");
using(SqlConnection connection = new SqlConnection(connection))
{
SqlCommand command = new SqlCommand(query.ToString(), connection);
command.Parameters.AddWithValue("@fields", fields.ToString());
command.Parameters.AddWithValue("@tables", tables.ToString());
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
奇怪的是,此操作失败,并显示消息必须声明表变量\"@ tables \".但是,正如您所看到的,它已经明确定义了.
The strange part is this fails with the message "Must declare the table variable \"@tables\". However as you can see, it's clearly been defined.
所以我的问题是:
- 您可以传递参数来定义 FROM中的表列表 陈述?
- 如果可以,为什么不 这个工作吗?
- Can you pass a parameter to define the table list in the FROM statement?
- If you can, why isn't this working?
推荐答案
SQL不支持对FROM子句进行参数化.因此,您必须使用动态SQL,或在将查询字符串提交到数据库之前创建/连接查询字符串.
SQL doesn't support the FROM clause to be parameterized. So you have to use either dynamic SQL, or create/concatenate the query string prior to submitting it to the database.
这篇关于您可以在SQL FROM语句中使用SQLParameter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文