在select查询中具有列名的sql查询字符串中使用字符串变量

时间:2013-01-20 11:37:13

标签: c# asp.net

我正在尝试将列名放在变量中,然后我在sql查询中使用此字符串:

string s="ID";

string sql="select '"+s+"' from table_name where name='abhk'";

cmd=new SqlCommand(sql_pics, con);

cmd.ExecuteNonQuery();

它表示ID ID is column name.

附近的语法错误不正确

4 个答案:

答案 0 :(得分:0)

string sql = "select "+s+" from table_name where name='abhk'";列名不能,也不应该是single quotes

中的字符串

答案 1 :(得分:0)

试试这个;

string sql = "select ID from table_name where name='abhk'";

答案 2 :(得分:0)

问题是您的查询将使用您当前的逻辑看起来如下:

select 'ID' from table_name where name = 'abhk'

您需要将sql字符串更改为:

string sql="select " + s + " from table_name where name='abhk'";

然而,这有点像黑客。

答案 3 :(得分:0)

单引号在这里不起作用,但我建议在列名前后放括号,而不是什么,以防列名包含空格或特殊字符:

string sql="select ["+s+"] from table_name where name='abhk'";