C#的SqlCommand - 不能用于列名的参数,如何解决? [英] C# SqlCommand - cannot use parameters for column names, how to resolve?
问题描述
有什么办法如何做到这一点?这不起作用:
Is there any way how to do that? This does not work:
SqlCommand command = new SqlCommand("SELECT @slot FROM Users WHERE name=@name; ");
prikaz.Parameters.AddWithValue("name", name);
prikaz.Parameters.AddWithValue("slot", slot);
我能想到的唯一的事情就是用SP和申报,并设置变量列。 。在我看来,有点ackward
The only thing I can think of is to use SP and declare and set the variable for the column. Seems to me a bit ackward.
推荐答案
您不能在普通的SQL做到这一点 - 如果你必须有可配置的列名(或表名,对于这个问题),你必须使用动态SQL - 有没有其他的方式来实现这一目标。
You cannot do this in regular SQL - if you must have configurable column names (or table name, for that matter), you must use dynamic SQL - there is no other way to achieve this.
string sqlCommandStatement =
string.Format("SELECT {0} FROM dbo.Users WHERE name=@name", "slot");
,然后使用在 sp_executesql的
存储过程。SQL服务器来执行SQL命令(并根据需要指定其他参数)
and then use the sp_executesql
stored proc in SQL Server to execute that SQL command (and specify the other parameters as needed).
动态SQL都有其优点和缺点 - 阅读的诅咒和动态SQL祝福通过SQL服务器MVP厄兰Sommarskog熟练编写的。
Dynamic SQL has its pros and cons - read the ultimate article on The Curse and Blessings of Dynamic SQL expertly written by SQL Server MVP Erland Sommarskog.
这篇关于C#的SqlCommand - 不能用于列名的参数,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!