C# SQL 多条件查询技巧

Posted jiangyunfeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于C# SQL 多条件查询技巧的主要内容,如果未能解决你的问题,请参考以下文章

c# linq 动态多条件查询语句的写法

用C#多条件查询,并把查询的条件显示在datagridview中

C# SQL条件查询语句where中使用变量的用法

ASP多条件查询怎么做?

asp.net c# 想实现条件能为空的多条件查询

SQL多条件查询安全高效比较