public static string SQLLikeEncode(string value, SQLLikeType type, string escapeChar = "\b") { string strRet = string.Empty; try { string input = value; string str2 = ""; string str = ""; if (input == null) { input = string.Empty; } input = Regex.Replace(Regex.Replace(Regex.Replace(input, "%", escapeChar + "%"), "%", escapeChar + "%"), "_", escapeChar + "_"); input = Regex.Replace(input, @"\[", escapeChar + "["); if ((type == SQLLikeType.PartMatch) | (type == SQLLikeType.InitialMatch)) { str = "%"; } if ((type == SQLLikeType.PartMatch) | (type == SQLLikeType.EndMatch)) { str2 = "%"; } strRet = "'" + str2 + Regex.Replace(input, "'", "''") + str + "' ESCAPE '" + escapeChar + "'"; } catch { strRet = ""; } return(strRet); }
//空格分割要查询的条件 组合like条件 public static string SQLLikeEncodeBySpace(string value, SQLLikeType type, string escapeChar = "\b") { string strRet = string.Empty; try { string input = value; string str2 = ""; string str = ""; if (input == null) { input = string.Empty; } input = Regex.Replace(Regex.Replace(Regex.Replace(input, "%", escapeChar + "%"), "%", escapeChar + "%"), "_", escapeChar + "_"); input = Regex.Replace(input, @"\[", escapeChar + "["); if ((type == SQLLikeType.PartMatch) | (type == SQLLikeType.InitialMatch)) { str = "%"; } if ((type == SQLLikeType.PartMatch) | (type == SQLLikeType.EndMatch)) { str2 = "%"; } strRet = "'" + str2 + Regex.Replace(input, "'", "''") + str + "' ESCAPE '" + escapeChar + "'"; //根据要求需要把查询条件改为 //如(输入的"上海血液" like 变成"%上%海%血%液%") 中间也需要% 所以修改如下 //========== //int a = 0; //string strvalue = Regex.Replace(input, "'", "''"); //string restr = ""; //string[] array = restr.Split(' '); //while (a < array.Length) //{ // restr += strvalue.Substring(a, 1) + "|"; // a++; //} //strRet = "'" + str2 + "[" + restr.Substring(0, restr.Length - 1) + "]" + str + "' ESCAPE '" + escapeChar + "'"; //========= } catch { strRet = ""; } return(strRet); }