asp.net 多字段模糊查询代码
程序员文章站
2022-05-30 23:29:06
string strfield = "id|classname|classadd"; string strkeywords ...
string strfield = "id|classname|classadd";
string strkeywords = this.tbxkeywords.text.trim();
string strsql = dbexe.searchtext("select * from class", strfield, strkeywords);
经常用到多字段的模糊查询,上面的函数可以实现,例如strkeywords值为“”时,可以输出:
select * from class where id like '%%' or classname like '%%' or classadd like '%%'
函数:
/// <summary>
/// 根据关键字实现多字段模糊查询
/// </summary>
/// <param name="sqlstr">select * from talbe sql语句</param>
/// <param name="sqltext">判断语句条件,是一个用|隔开的字符串</param>
/// <param name="keywords">关键字</param>
public static string searchtext(string strsql, string strfield, string keywords)
{
stringbuilder sb = new stringbuilder(strsql);
if (strfield != string.empty)
{
sb.append(" where ");
string[] arrkey = strfield.split('|');
for (int i = 0; i < arrkey.length; i++)
{
sb.append(arrkey[i] + " like '%" + keywords + "%' or ");
}
string str = sb.tostring();
//去除最后一个"or"
if (str.indexof("or") >= 0)
{
return str.remove(str.lastindexof("or"));
}
return str;
}
return strsql;
}
string strkeywords = this.tbxkeywords.text.trim();
string strsql = dbexe.searchtext("select * from class", strfield, strkeywords);
经常用到多字段的模糊查询,上面的函数可以实现,例如strkeywords值为“”时,可以输出:
select * from class where id like '%%' or classname like '%%' or classadd like '%%'
函数:
/// <summary>
/// 根据关键字实现多字段模糊查询
/// </summary>
/// <param name="sqlstr">select * from talbe sql语句</param>
/// <param name="sqltext">判断语句条件,是一个用|隔开的字符串</param>
/// <param name="keywords">关键字</param>
public static string searchtext(string strsql, string strfield, string keywords)
{
stringbuilder sb = new stringbuilder(strsql);
if (strfield != string.empty)
{
sb.append(" where ");
string[] arrkey = strfield.split('|');
for (int i = 0; i < arrkey.length; i++)
{
sb.append(arrkey[i] + " like '%" + keywords + "%' or ");
}
string str = sb.tostring();
//去除最后一个"or"
if (str.indexof("or") >= 0)
{
return str.remove(str.lastindexof("or"));
}
return str;
}
return strsql;
}
下一篇: 秦始皇大胜匈奴后,为何选择修建长城?