当前位置:编程学习 > C#/ASP.NET >>

sql语句拼接实现多条件查询

想请教下各位,实现多条件查询的方法,以前知道一个通过数据库sql语句拼接的方法实现,但是不知道代码怎么写 --------------------编程问答--------------------

     string sql = "select * from 表名 where 1=1";
     if(condition1!=string.Empty)
     {
        sql +="and condition1对应字段='"+conditon1+"'";
     }
    ……
--------------------编程问答--------------------  
参考

             StringBuilder sb = new StringBuilder();
                 if(userName!=null&&userName!="")
                 {
                     sb.Append(" and name=" + UserName);
                 }
             string sql = "select * from tb where 1=1 "+sb; --------------------编程问答--------------------
引用 1 楼 pwxcomer 的回复:
SQL code

     string sql = "select * from 表名 where 1=1";
     if(condition1!=string.Empty)
     {
        sql +="and condition1对应字段='"+conditon1+"'";
     }
    ……


++

主要是string sql = "select * from 表名 where 1=1";

这个where 1=1 比较巧妙! --------------------编程问答-------------------- 恩恩,加个条件where 1=1就是永远都成立的情况下 --------------------编程问答--------------------  1=1

是为了 后面没有满足条件加载的情况下

衔接 where的 --------------------编程问答--------------------
引用 5 楼 wxr0323 的回复:
 1=1

是为了 后面没有满足条件加载的情况下

衔接 where的


1=1 是什么意思呢? --------------------编程问答--------------------
引用 6 楼 mazhaojuan 的回复:
1=1 是什么意思呢?

1=1永远是真,加1=1的目的是为了接后面的条件的,否则 where and 条件 and 条件……是有语法错误的 --------------------编程问答-------------------- 如是没有满足的条件,sql语句加上 1=1 不然where会报错
引用 6 楼 mazhaojuan 的回复:
引用 5 楼 wxr0323 的回复:

1=1

是为了 后面没有满足条件加载的情况下

衔接 where的


1=1 是什么意思呢?
--------------------编程问答-------------------- --------------------编程问答-------------------- where 1=1 太巧妙了!高手! --------------------编程问答--------------------
引用 1 楼 pwxcomer 的回复:

     string sql = "select * from 表名 where 1=1";
     if(condition1!=string.Empty)
     {
        sql +="and condition1对应字段='"+conditon1+"'";
     }
    ……

这样拼接要被sql注入的吧
改成参数化
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,