?
C# SQL 多条件查询技巧
2013-03-05 15:04?
5843人阅读?
?
收藏?
举报
@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@ (编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|