asp.net 多欄位模糊查詢代碼_實用技巧
來源:互聯網
上載者:User
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;
}