C# SQL 多条件查询技巧
2016-08-09 10:52
399 查看
C# SQL 多条件查询技巧
2013-03-05 15:04 5843人阅读 评论(0) 收藏 举报分类:
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# SQL 多条件查询技巧
- C# SQL多条件查询拼接技巧
- util-C# 复杂条件查询(sql 复杂条件查询)查询解决方案
- C# SqlServer 未定字段未定条件的组合查询写法
- 必须知道的SQL编写技巧,多条件查询不拼字符串的写法
- C#中使用Sql对Excel条件查询
- 关于多重条件的搜索查询(sql server+c#)
- 或许你不知道的10条SQL技巧 原创 2017-07-16 58沈剑 架构师之路 这几天在写索引,想到一些有意思的TIPS,希望大家有收获。 一、一些常见的SQL实践 (1)负向条件查询不能使用索
- 必须知道的SQL编写技巧,多条件查询不拼字符串的写法
- 必须知道的SQL编写技巧,多条件查询不拼字符串的写法
- C#连接SQL多条件复杂查询
- c#将查询到SQL的数据放到DataTable里,再根据条件查询放到新的表里
- SQL查询日期条件则无法返回正常结果
- SQL学习之查询技巧 查询第3的数据 用一条语句分组,排序 并查询某一排名
- sql数据的like查询条件方案
- SQL学习之查询技巧 求某日期所在月份的天数
- SQL学习之查询技巧 排他查询 只是用过某商品的顾客
- SQL查询语句对象化的实现(C#
- SQL中以count及sum为条件的查询