C# SQL 多条件查询技巧
#region 多条件搜索时,使用List集合来拼接条件(拼接Sql)
StringBuilder sql = new StringBuilder("select * from PhoneNum");
List<string> wheres = new List<string>();
if (cboGroup.SelectedIndex != 0)
{
wheres.Add(" ptypeid=" + cboGroup.Text.Split('|')[0]);
}
if (txtSearchName.Text.Trim().Length > 0)
{
wheres.Add(" pname like '%" + txtSearchName.Text.Trim() + "%'");
}
if (txtSearchCellPhone.Text.Trim().Length > 0)
{
wheres.Add(" pcellphone like '%" + txtSearchCellPhone.Text.Trim() + "%'");
}
//判断用户是否选择了条件
if (wheres.Count > 0)
{
string wh = string.Join(" and ", wheres.ToArray());
sql.Append(" where " + wh);
}
#endregion
#region 多条件搜索使用带参数的sql语句
StringBuilder sql = new StringBuilder("select * from PhoneNum");
List<string> wheres = new List<string>();
List<SqlParameter> listParameter = new List<SqlParameter>();
if (cboGroup.SelectedIndex != 0)
{
wheres.Add(" ptypeid=@typeid ");
listParameter.Add(new SqlParameter("@typeid", cboGroup.Text.Split('|')[0]));
}
if (txtSearchName.Text.Trim().Length > 0)
{
wheres.Add(" pname like @pname ");
//pname like '%乔%'
//pname liek '%'+@pname+'%'
listParameter.Add(new SqlParameter("@pname", "%" + txtSearchName.Text.Trim() + "%"));
}
if (txtSearchCellPhone.Text.Trim().Length > 0)
{
wheres.Add(" pcellphone like @cellphone ");
listParameter.Add(new SqlParameter("@cellphone", "%" + txtSearchCellPhone.Text.Trim() + "%"));
}
//判断用户是否选择了条件
if (wheres.Count > 0)
{
string wh = string.Join(" and ", wheres.ToArray());
sql.Append(" where " + wh);
}
SqlHelper.ExecuteDataTable(sql.ToString(), listParameter.ToArray());
#endregion
最新文章
- oracle 字符乱码问题解决方案
- ffmpeg mp3 to m3u8
- 【杂记】SQL篇
- Golang学习 - bufio 包
- BZOJ2298: [HAOI2011]problem a
- 得到某个进程所有线程ID和入口地址
- 仿微博——MJExtension之字典转模型
- Android 应用间的集成
- Qt编程学习网站
- MyEclipse性能调优初体验
- 链接分析算法之:主题敏感PageRank
- 用Open SSH生成公钥和私钥(Win)
- c语言——第0次作业
- C#备份及还原数据库的实现
- [trouble] error connecting to master &#39;repl@192.168.1.107:3306&#39; - retry-time: 60 retries: 86400
- Ubuntu 远程使用ssh 开启服务器终端的方法
- Selenium Webdriver元素定位的八种常用方式(转载)
- 有关Linux的.a、.so和.o文件(转)【原文章有些错误,自己已更改】
- Dalvik源码阅读笔记(二)
- luogu2038 [NOIp2014]无线网络发射器选址 (前缀和)