C# SqlCommand - 不能使用列名参数,如何解决? [英] C# SqlCommand - cannot use parameters for column names, how to resolve?

查看:22
本文介绍了C# SqlCommand - 不能使用列名参数,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点?这不起作用:

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

然后使用 SQL Server 中存储的 sp_executesql proc 来执行该 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 Server MVP Erland 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆