日期:2014-05-16  浏览次数:20958 次

oracle 中函数拼凑sql语句并返回值的问题
现在函数有两个参数 一个是type_in(nvarchar2),startdate_in(nvarchar2)
根据两个参数拼凑成sql语句 然后返回sql语句执行的值.

参数值:
type_in='D'
startdate_in=' startdate>=开始日期 and startdate<=结束日期 '


sql语句大概是:

select sum(total) from 表 where type=type_in || startdate_in  

请问返回这个值的函数怎么写?

------解决方案--------------------
开始日期和结束日期,是通过函数传进来的么?
------解决方案--------------------
SQL code

create or replace function f_test(type_in in varchar2,startdate_in in varchar2)
return int is 
  i_num int;
begin
  execute immediate 'select sum(total) from table where type='''||type_in||
                    ''' and '||startdate_in into i_num;
  return i_num;
end;

------解决方案--------------------
type这列的值是什么?
下面这句:select sum(total) from 表 where type=type_in || startdate_in
应该是这样的吧:
select sum(total) from 表 where type=type_in and startdate_in
对吧?
------解决方案--------------------
2楼的动态SQL很好用:
探讨
SQL code

create or replace function f_test(type_in in varchar2,startdate_in in varchar2)
return int is
i_num int;
begin
execute immediate 'select sum(total) from table where type='''||type……

------解决方案--------------------
SQL code

CREATE OR REPLACE FUNCTION get_sql(type_in VARCHAR2,startdate_in VARCHAR2)
RETURN NUMBER IS res NUMBER(10,2);
BEGIN
       out_sql:='select sum(total) from tab where type ='||type_in||' and '|| startdate_in;
       EXECUTE IMMEDIATE out_sql INTO  res;
       RETURN res;
END