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;
}
您可能感兴趣的文章: