日期:2014-05-17  浏览次数:21109 次

oracle 动态拼接语句并返回查询结果集

--oracle 动态拼接语句并返回查询结果集
--以前用MS-SQL 现在对oracle中的语句拼接没有经验
--希望各位大侠不吝赐教
declare
  q varchar2(4000);
begin
  q := 'select *';
  q := q || ' from BB_C15';
  q := q || ' Where TAIZHDJYF =' || '2013';
  q := q || ' and CHENBDW = ' || '14';
  if '12' != '' then
    q := q || ' and qiymch = ' || '';
  end if;
  if '12' != '' then
    q := q || ' and FeiWLB = ' || '';
  end if;
   execute immediate q ;
end;
oracle

------解决方案--------------------

create table test(id number, name varchar2(50), sal number);
insert into test values(1066, 'xiaoli', 3000);
insert into test values(1067, 'xiaowang', 3500);
insert into test values(1068, 'xiaozh', 3800);
select * from test;

declare  q varchar2(4000); 
rec test%rowtype;
begin  
q := 'select * from TEST Where ID > 1066 '; 
if 1 <> 3 then
q := q 
------解决方案--------------------
 'and sal = 3500';
end if;
  
dbms_output.put_line(q); --你可以把拼接的字符串打印出来看看对不对,能不能执行。

execute immediate q 
into rec; 
--用select做动态查询时,要加into去获得查询出来的值,我定义了一个记录类型的变量,能获得一条的值。
dbms_output.put_line('rec: ' 
------解决方案--------------------
 rec.name 
------解决方案--------------------
 ' ' 
------解决方案--------------------
 rec.sal); 
end;