且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL命令中将列名作为参数传递?

更新时间:2023-09-23 14:01:58

表的结构是静态的,在很多情况下应该是结构查询表的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.