在SYS_REFCURSOR中执行动态sql语句

前端之家收集整理的这篇文章主要介绍了在SYS_REFCURSOR中执行动态sql语句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在plsql中执行一个动态的sql,并将结果返回到sys_refcursor?我已经粘贴了我的尝试太远了,但dosnt接缝工作,这是错误我通过我的 java应用程序

ORA-01006: bind variable does not
exist ORA-06512: at
“LIVEFIS.ERC_REPORT_PK”,line 116
ORA-06512: at line 1

但是这可能是由java错误的一切,所有接缝编译好的soo我不知道.

procedure all_carers_param_dy (pPostcode in carer.postcode%type,pAge Number,pReport out SYS_REFCURSOR) is
  begin
    declare
      lsql  varchar2(500) :='SELECT c.id FROM carer c,cared_for cf,carer_cared_for ccf '
          ||' where c.id = ccf.carer_id (+)'
          ||' AND cf.id (+) = ccf.cared_for_id';

    begin

     if pPostcode is not null and pAge <= 0 then
        lsql := lsql||' AND c.postcode like ''%''|| upper(pPostcode)||''%''';
      elsif pPostcode is null and pAge > 0 then 
         lsql := lsql||' AND ROUND((MONTHS_BETWEEN(sysdate,c.date_of_birth)/12)) = pAge';
      elsif pPostcode is not null and pAge > 0 then
         lsql := lsql ||' AND ROUND((MONTHS_BETWEEN(sysdate,c.date_of_birth)/12)) = pAge'
                      ||' AND c.postcode like ''%''|| upper(pPostcode)||''%''';
      end if;


        execute immediate lsql
        into pReport;


    end;
  end;

Im新到plsql甚至更新的动态sql soo任何帮助/建议将被大大的apreciated.

再次感谢

乔恩

解决方法

你必须绑定参数pAge和pPostcode.在动态sql中,您将以冒号(:)前缀.如果使用EXECUTE IMMEDIATE或OPEN … FOR,您将通过位置绑定参数,这就是为什么我重命名它们:示例中的P1和P2:
DECLARE
   lsql VARCHAR2(500) := 'SELECT c.id 
                            FROM carer c,carer_cared_for ccf 
                           WHERE c.id = ccf.carer_id (+)
                             AND cf.id (+) = ccf.cared_for_id';
BEGIN
   IF pPostcode IS NULL THEN
      lsql := lsql || ' AND :P1 IS NULL';
   ELSE
      lsql := lsql || ' AND c.postcode like ''%''|| upper(:P1)||''%''';
   IF pPostcode pAge > 0 THEN
      lsql := lsql || ' AND :P2 = ROUND((MONTHS_BETWEEN(sysdate,c.date_of_birth)/12))';
   ELSE
      lsql := lsql || ' AND nvl(:P2,-1) <= 0';
   END IF;
   OPEN pReport FOR lsql USING pPostcode,pAge;
END;

注意:编译时必须知道绑定变量的数量和位置,这就是为什么我经常使用上面的结构(即使不使用参数也添加到它的位置).将一个重言式(如AND:P1 IS NULL)添加查询中不会影响其解释计划.

猜你在找的MsSQL相关文章