加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

C# SQL 多条件查询技巧

发布时间:2021-07-06 05:54:58 所属栏目:大数据 来源: https://blog.csdn.net/kasama1
导读:? C# SQL 多条件查询技巧 2013-03-05 15:04 ? 5843人阅读 ? 评论(0) ? 收藏 ? 举报 @H_404_24@? 分类: C#_sql多条件查询技巧 ??????????? #region 多条件搜索时,使用List集合来拼接条件(拼接sql)@H_404_24@ ??????????? StringBuilder sql = new StringB
?

C# SQL 多条件查询技巧

? 5843人阅读? 评论(0)? 收藏? 举报

@H_404_24@? 分类:

??????????? #region 多条件搜索时,使用List集合来拼接条件(拼接sql)@H_404_24@


??????????? StringBuilder sql = new StringBuilder("select * from PhoneNum");
??????????? List<string> wheres = new List<string>();
??????????? if (cboGroup.SelectedIndex != 0)
??????????? {
??????????????? wheres.Add(" ptypeid=" + cboGroup.Text.Split('|')[0]);
??????????? }@H_404_24@

??????????? if (txtSearchName.Text.Trim().Length > 0)
??????????? {
?????????????????wheres.Add(" pname like '%" + txtSearchName.Text.Trim() + "%'");
??????????? }@H_404_24@

??????????? if (txtSearchCellPhone.Text.Trim().Length > 0)
??????????? {
???????????????? wheres.Add(" pcellphone like '%" + txtSearchCellPhone.Text.Trim() + "%'");
??????????? }@H_404_24@


??????????? //判断用户是否选择了条件
??????????? if (wheres.Count > 0)
??????????? {
??????????????? string wh = string.Join(" and ",wheres.ToArray());
??????????????? sql.Append(" where " + wh);
??????????? }
??????????? #endregion@H_404_24@

?@H_404_24@

?@H_404_24@

?@H_404_24@

??????????? #region 多条件搜索使用带参数的sql语句@H_404_24@

??????????? StringBuilder sql = new StringBuilder("select * from PhoneNum");
??????????? List<string> wheres = new List<string>();
??????????? List<sqlParameter> listParameter = new List<sqlParameter>();@H_404_24@

??????????? if (cboGroup.SelectedIndex != 0)
??????????? {
??????????????? wheres.Add("?ptypeid=@typeid?");
??????????????? listParameter.Add(new sqlParameter("@typeid",cboGroup.Text.Split('|')[0]));
??????????? }@H_404_24@

??????????? if (txtSearchName.Text.Trim().Length > 0)
??????????? {
??????????????? wheres.Add(" pname like @pname ");
??????????????? //pname like '%乔%'
??????????????? //pname liek?'%'+@pname+'%'
??????????????? listParameter.Add(new sqlParameter("@pname","%" + txtSearchName.Text.Trim() + "%"));
??????????? }@H_404_24@

??????????? if (txtSearchCellPhone.Text.Trim().Length > 0)
??????????? {
??????????????? wheres.Add(" pcellphone like @cellphone ");
??????????????? listParameter.Add(new sqlParameter("@cellphone","%" + txtSearchCellPhone.Text.Trim() + "%"));
??????????? }@H_404_24@


??????????? //判断用户是否选择了条件
??????????? if (wheres.Count > 0)
??????????? {
??????????????? string wh = string.Join(" and ",wheres.ToArray());
??????????????? sql.Append(" where " + wh);
??????????? }@H_404_24@

?@H_404_24@

??????????? sqlHelper.ExecuteDataTable(sql.ToString(),listParameter.ToArray());
??????????? #endregion@H_404_24@

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读