当前位置: 代码迷 >> Oracle开发 >> 依据表数据动态拼接查询语句
  详细解决方案

依据表数据动态拼接查询语句

热度:116   发布时间:2016-04-24 06:33:23.0
根据表数据动态拼接查询语句
各位大大,有个存储过程不会写,还请大大指教:
有个条件表a,
name,operator,logic,code
abc,      =             or       331
abc      =              or       448
abc      =              or       899
bcd     !=             and     345
bcd     !=             and      987

要拼接的sql查询是  select  * from b where(某name下的全部记录)


------解决思路----------------------

-- 11.2 下,你可以试试 listagg 函数。
create table m as 
select 'cc'  name , 'and' logic , '=' op ,'555' as code from dual union all
select 'cc'  name , 'and' logic , '=' op ,'444' as code from dual union all
select 'name'  name , 'and' logic , '=' op ,'100' as code from dual union all
select 'name'  name , 'and' logic , '=' op ,'101' as code from dual union all
select 'name'  name , 'and' logic , '=' op ,'111' as code from dual

with mt as (
select  listagg(' ' 
------解决思路----------------------
 name 
------解决思路----------------------
 op 
------解决思路----------------------
 code 
------解决思路----------------------
 ' ' 
------解决思路----------------------
 logic  ,'')   within group (order by name) c
from m where name = 'name'
)
select substr(c,1,length(c) -4 )   from mt 

------解决思路----------------------
先把or的拼接起来,然后再与and进行拼接

select listagg(str,' and ') within group(order by rownum) from(
    select '('
------解决思路----------------------
listagg('code'
------解决思路----------------------
operator
------解决思路----------------------
code,' or ') within group(order by rownum)
------解决思路----------------------
')'  str
    from a where name='abc' and logic='or'
    union all
    select 'code'
------解决思路----------------------
operator
------解决思路----------------------
code str
    from a where name='abc' and logic='and'
)
  相关解决方案