微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# SQL 多条件查询技巧

 

C# SQL 多条件查询技巧

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

  分类

            #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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐