C# SQL命令搜索
上面的命令有什么问题?C# SQL命令搜索,c#,sql-server,C#,Sql Server,上面的命令有什么问题? 我收到错误消息“靠近@asr”。搜索字符串周围缺少引号,一个括号太多: SqlCommand cmd = new SqlCommand("select * from [Table] where Col1 like %@astr% or Col2 like %@astr% or Col3 like %@astr%)", con); cmd.Parameters.AddWithValue("@astr", st);
我收到错误消息“靠近@asr”。搜索字符串周围缺少引号,一个括号太多:
SqlCommand cmd = new SqlCommand("select * from [Table] where Col1 like
%@astr% or Col2 like %@astr% or Col3 like %@astr%)", con);
cmd.Parameters.AddWithValue("@astr", st);
如果astr是字符串。你可以试试这个
SqlCommand cmd = new SqlCommand(
@"select * from [Table]
where Col1 like '%' || @astr || '%'
or Col2 like '%' || @astr || '%'
or Col3 like '%' || @astr || '%'", con);
必须在变量中指定通配符(
%
),然后在查询中删除通配符
string astr = "ABC";
SqlCommand cmd = new SqlCommand("select * from [Table] where Col1 like %" + astr + "% or Col2 like %" + astr + "% or Col3 like %" + astr + "%", con);
cmd.Parameters.AddWithValue("@astr", st);
尝试删除
)
在sql查询的最后,使用这个像%@astr%
哦!非常感谢。三个小时,我甚至想不出来。没什么,发生在忙碌的一天:-)先生!似乎%不能与@搭配。。因为在我移除了),我仍然有那个问题。我该怎么办?我加了答案,请核对。是| |吗?我从未在SQL查询中看到过这一点。它是连接字符串的标准SQL运算符,例如,“hello”| |“world”
。几乎所有的数据库管理系统都支持这种语法。但也有例外。例如,我认为SQLServer使用了非标准的+
。在MySQL中,它可能取决于某些设置,因此可能必须使用CONCAT
。
st = string.Format("%{0}%", st); // in case your search string don't have wild characters..
SqlCommand cmd = new SqlCommand("select * from [Table] where Col1 like
%@astr% or Col2 like @astr or Col3 like @astr)", con);
cmd.Parameters.AddWithValue("@astr", st);