需求:按照姓名或拼音简码在数据库表中进行模糊查询,如果输入是中文,查询Name字段,如果是字母查询PyJm字段
1.不用正则表达式的方式
int l = strName.Length;
char[] cha = strName.ToCharArray();
for(int i =0 ;i<strName.Length;i++)
{
if(Convert.ToInt32(cha[i])>255)
l+=2;
if(Char.IsLetter(strName,i))
l-=1;
}
if(l==0)
sql+=" and Xf_ZfJbXx.PyJm like '%"+strName+"%'";
else
sql+=" and Xf_ZfJbXx.Name like '%"+strName+"%'";
2.用正则表达式的方式
//增加正则表达式的命名空间
using System.Text.RegularExpressions;
/// <summary>
/// 判断是否为拼音
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
public static bool IsPy(string strName)
{
return Regex.IsMatch(strName,"^[A-Za-z]|[0-9]$");
}
/// <summary>
/// 选人界面用SQL(当前表)
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
public static string SearchPeopleSql(string strName)
{
string sql = " and Name like '%"+strName+"%' ";
if(IsPy(strName))
{
sql = " and PyJm like '%"+PyJm+"%' ";
}
return sql;
}