是否可以在plsql中执行动态sql并将结果返回到sys_refcursor中?我已经将尝试粘贴得太远了,但是没有接缝能正常工作,这是我无法通过我的Java应用程序的错误



但这可能是Java误解的东西,所有的东西都无法正确编译。

 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;

我不是plsql的新手,甚至是动态sql的新手,所以将不胜感激任何帮助/建议。

再次感谢

乔恩

最佳答案

您将必须绑定(bind)参数pAgepPostcode。在动态SQL中,您可以在它们前面加上一个冒号(:)。如果使用EXECUTE IMMEDIATEOPEN ... FOR,则将通过位置绑定(bind)参数,这就是为什么在示例中将它们分别重命名为:P1和:P2的原因:

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 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;

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

09-13 07:21