简体   繁体   English

列名作为参数

[英]column name as parameter

I have some columns like text_en, text_es, text_de in a SQL table. 我在SQL表中有一些像text_en,text_es,text_de这样的列。 Now I want to retrieve the value from just one column depending on the language. 现在我想根据语言从一列中检索值。 So I created an sql string SELECT @textfield FROM <table> and in the vb code I use cmd.AddWithValue("textfield", "text_" + lang) But sql returns the name of the column instead of the value of that column. 所以我创建了一个sql字符串SELECT @textfield FROM <table> ,在vb代码中我使用了cmd.AddWithValue("textfield", "text_" + lang)但是sql返回列的名称而不是该列的值。 How can I get the value? 我怎样才能获得价值?

You can also do 你也可以

SELECT CASE @textfield
         WHEN 'text_en' THEN text_en
         WHEN 'text_es' THEN text_es
         WHEN 'text_de' THEN text_de
       END AS local_text
FROM TableName

Don't pass it as a parameter, pass it as a string literal. 不要将其作为参数传递,将其作为字符串文字传递。 Your sql statement should be in the form: 你的sql语句应该是以下形式:

string col1name = 'somename';
string sql = 'SELECT ' + col1name + ' FROM TableName';

But if you have a parameter passed to the WHERE clause you should pass it as a parameter like what you did in your question. 但是,如果您有一个参数传递给WHERE子句,则应像在问题中一样将其作为参数传递。

Note that: Your query, this way is vulnerable to SQL Injection . 请注意:您的查询,这种方式容易受到SQL Injection的攻击。 In your case, you can pass your concatenated SQL statement to a stored procedure then use sp_executesql , not EXEC() . 在您的情况下,您可以将连接的SQL语句传递给存储过程,然后使用sp_executesql ,而不是EXEC()

You can't use variables are column names in SQL, not like this, anyway. 你不能在SQL中使用变量是列名,反正不是这样的。

You need to use dynamic SQL in order to specify column names like this. 您需要使用动态SQL来指定像这样的列名。

I suggest reading The Curse and Blessings of Dynamic SQL for a comprehensive treatment of the subject. 我建议阅读动态SQL的诅咒和祝福,以全面处理该主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM