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;
}