如何在SQL命令中将列名作为参数传递? [英] How to pass column name as parameter in SQL command?

查看:369
本文介绍了如何在SQL命令中将列名作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将select命令中的列名作为参数传递。



i希望通过提供列名作为参数来选择最佳匹配值,因为我的值列名称和值将是相同的。



我尝试过:



示例代码:



How Can i pass column name in select command as parameter.

i want to select best match values by providing column name as parameter because my value column name and value will be same.

What I have tried:

Sample Code:

string mname="C-1";//It is column name 
string sname="1.2"; 
MySqlCommand co = new MySqlCommand("select @mname from capacity_master where(nsize=@nsize)", cn);
                co.Parameters.AddWithValue("@mname", mname);
                co.Parameters.AddWithValue("@nsize", sname);
                using(MySqlDataReader cor = co.ExecuteReader())
                {
                    while (cor.Read())
                    {
                        capinhrs = 11;
                        capinkgs = double.Parse(cor[0].ToString());
                    }
                }

推荐答案

表的结构是静态的,在很多情况下应该是结构查询表的SQL语句。在某些情况下,您可能需要SQL语句是动态的,但这并不常见。



你说:

The structure of the table is static and in many cases so should be the structure of the SQL statement querying the table. In some scenarios you may need the SQL statement to be dynamic but that is not very common.

You say:
i want to select best match values by providing column name as parameter because my value column name and value will be same.



通常你不选择结果列基于值匹配而不是您选择查询的列,因为模型定义它包含您感兴趣的数据。所以上面的语句听起来表明您使用表的方式有问题。但是要回答你的问题,在使用动态SQL语句时,需要明确定义语句的结构部分,这样就不能将列名,表名等作为参数传递。如果您使用动态SQL,那么您需要将名称连接到语句中。



但是如上所述它看起来不像动态SQL会是正确的要走的路。


Normally you don't choose the result column based on a value match instead you choose the column to your query because the model defines that it contains the data you're interested in. So the statement above does sound that there is something wrong in the way you use the table.

But to answer your question, when using dynamic SQL statements, the structural parts of the statements need to be explicitly defined so you cannot pass column names, table names etc as parameters. In case you would use dynamic SQL then you would need to concatenate the names into the statement.

But as said it doesn't look like dynamic SQL would be the correct way to go.


引用:

我知道之前询问过这个问题但所有答案都与存储有关程序,我想从表。

I know this question is asked before but all answers related to stored procedure and i wanted from table.





对于存储过程或命令,它完全相同。列名是列名。



但是......在您的级别上,想要这样做通常表明您的数据库设计有问题。除非您的设计存在严重缺陷,否则您不需要将列名作为参数玩。



It's exactly the same for a stored procedure or a command. A column name is a column name.

But ... at your level, wanting to do that is normally a sign that your database design is faulty. You should not need to be "playing" with column names as parameters unless you have some serious flaws in your design.


这篇关于如何在SQL命令中将列名作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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