Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在sql查询中使用字符串变量在select查询中具有列名的字符串_C#_Asp.net - Fatal编程技术网

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

C# 在sql查询中使用字符串变量在select查询中具有列名的字符串,c#,asp.net,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是列名。它应该是string sql=“select”+s+”from table_name where name='

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

string s="ID";

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

cmd=new SqlCommand(sql_pics, con);

cmd.ExecuteNonQuery();

它说ID附近有不正确的语法错误
ID是列名。

它应该是
string sql=“select”+s+”from table_name where name='abhk'
列名不能也不应该是包含在
单引号中的字符串

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

问题是,使用当前逻辑,您的查询将如下所示:

select 'ID' from table_name where name = 'abhk'
您需要将sql字符串更改为:

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

但是,这是一个小技巧。

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

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

你使用哪个数据库?