C# 在sql查询中使用字符串变量在select查询中具有列名的字符串
我尝试将列名放入变量中,然后在sql查询中使用此字符串,如下所示: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='
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'";
你使用哪个数据库?