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 '%阿会楠%'
函数:
///
/// 根据关键字实现多字段模糊查询
///
/// select * from talbe sql语句
/// 判断语句条件,是一个用|隔开的字符串
/// 关键字
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;
}
本文作者:佚名 来源:本站原创
CIO之家 www.ciozj.com 微信公众号:imciow