select * from 表A
where 表A.id = xxx  --这一条件是当某变量nos值为'id'时追加
and 表A.name = xxx  --这一条件是当某变量lng值为'name'时追加
and 表A.data = xxx  --这一条件是当某变量pid值为'data'时追加即分别判断变量nos,lng,pid的值,值符合要求时,才追加相应的条件,值不符时,不追加该条件
如果三个变量值都不符合,实际就等同于
select * from 表A也有可能是这样,只有lng值符合,则等同于
select * from 表A where 表A.name = xxx
请问怎么写?case when能做到吗?要进行语句拼接吗?

解决方案 »

  1.   

    select * from table where (var1='123' and col1='***') or  (var2='123' and col2='***')
    or  (var3='123' and col3='***')
      

  2.   

    在where中case when不好做  1楼应该是最简单的方法了 如果麻烦点一个一个拼起来select * from tb1 A where A.id = 'xxx' and nos='id'
    union all
    select * from tb1 A where A.name ='xxx' and lng='name'
    union all
    select * from tb1 A where A.data = 'xxx' and pid='date'
     总觉得有点矛盾,那个变量是参数还是什么呢?如果3个值都不符合 不是就查不到数据了么? 
      如果是传的参数为空还要查出所有数据的话 select * from tb1 A where (A.id = 'xxx' or 'xxx' is null) and nos='id'
      

  3.   


    select * from 表A
    where (nos is null or 表A.id = nos ) 
    and (lng is null or 表A.name = lng ) 
    and (pid is null or 表A.data = pid ) 
      

  4.   

    其实这个select语句是在一个存储过程里的,那三个变量是存储过程要接受的3个参数,为的就是区别不同情况下有不同的where条件
      

  5.   

    如果是SQL语句 1楼可以了。。如果在过程里面就用case when 不错
      

  6.   

    select * 
    from table 表A
    where 表A.id like nos
    and 表A.name like lng
    and 表A.data like pid
      

  7.   

    var
      sSql varchar2(2000);
    begin
      sSql := ' select * from 表A where 1=1 ';
      if nos = 'id' then
        sSql := sSql||' and 表A.id = xxx ';
      if lng = 'name' then
        sSql := sSql||' and 表A.name = xxx ';
      if pid = 'data' then
        sSql := sSql||' and 表A.data = xxx '; 
      execute immediate sSql;
    end;
      

  8.   


    var
      sSql varchar2(2000);
    begin
      sSql := ' select * from 表A where 1=1 ';
      if nos = 'id' then
      sSql := sSql||' and 表A.id = xxx ';
      if lng = 'name' then
      sSql := sSql||' and 表A.name = xxx ';
      if pid = 'data' then
      sSql := sSql||' and 表A.data = xxx ';  
      execute immediate sSql;
    end;