Can i use REGEXP_LIKE as a condition with IF in a PL/SQL block

谁说胖子不能爱 提交于 2021-02-11 07:22:30

问题


I'm trying to create a function designed to traverse a tree of organisational units filtering out some based on their level in the tree structure and weather they appear on our intranet page. The input to the function is the ORG_UNIT_ID of the starting unit, a flag to show if we should care about the intranet flag and a comma separated list of levels. For instance '2,3'. I'm trying to use REGEXP_LIKE in conjunction with an ELSEIF inside a loop to run up the tree until I hit the first eligible parent unit.

T_STOP is the control variable for the loop. R_ORG_UNIT_OVER is used to query meta-data on the above unit. During the loops first pass this will be the unit above the one passed as input to the function.

The cursor definition:

CURSOR C_ORG_UNIT_OVER(V_ORG_UNIT_ID ORG_UNIT.ORG_UNIT_ID%TYPE) IS
  SELECT  ORUI.ORG_UNIT_ID
  ,       ORUI.ORG_LEVEL
  ,       ORUI.SHOW_ON_INTRANET
FROM    ORG_UNIT ORUI
JOIN    ORG_UNIT_PARENT OUPA ON ORUI.ORG_UNIT_ID=OUPA.ORG_UNIT_ID_PARENT
WHERE   OUPA.ORG_UNIT_ID = V_ORG_UNIT_ID;

The failing code segment in the loop:

IF R_ORG_UNIT_OVER.SHOW_ON_INTRANET = 'N' THEN
  T_ORG_UNIT_ID := R_ORG_UNIT_OVER.ORG_UNIT_ID;
ELSEIF REGEXP_LIKE (P_SKIP_LEVEL, '(^|,)' || R_ORG_UNIT_OVER.ORG_LEVEL || '($|,)') THEN
  T_ORG_UNIT_ID := R_ORG_UNIT_OVER.ORG_UNIT_ID;
ELSE
  T_STOP := 'Y';
END IF;

However this code always throws a PLS-00103 error on the REGEXP_LIKE symbol. Is there some sort of limitation or alternate way in which REGEXP_LIKE works when used as a condition in a PL/SQL IF/ELSEIF block as opposed to in a regular query?


回答1:


PL/SQL uses ELSIF, not ELSEIF. With your edit your code does get the error you described; with this it doesn't:

IF R_ORG_UNIT_OVER.SHOW_ON_INTRANET = 'N' THEN
  T_ORG_UNIT_ID := R_ORG_UNIT_OVER.ORG_UNIT_ID;
ELSIF REGEXP_LIKE (P_SKIP_LEVEL, '(^|,)' || R_ORG_UNIT_OVER.ORG_LEVEL || '($|,)') THEN
  T_ORG_UNIT_ID := R_ORG_UNIT_OVER.ORG_UNIT_ID;
ELSE
  T_STOP := 'Y';
END IF;



回答2:


Yes you can.

declare 
    testvar varchar2(20) := 'Kittens';
begin
    if regexp_like(testvar, '^K') then
        dbms_output.put_line(testvar || ' matches ''^K''');
    end if;
end;

Kittens matches '^K'

PL/SQL procedure successfully completed.

Include some test data and I'll try to see what's not working as expected. For example,

declare 
    p_skip_level number := 2;
    org_level number := 3;
begin
    if regexp_like (p_skip_level, '(^|,)' || org_level || '($|,)')
    then
        dbms_output.put_line('Matched');
    else
        dbms_output.put_line('Not matched');
    end if;
end;


来源:https://stackoverflow.com/questions/40547587/can-i-use-regexp-like-as-a-condition-with-if-in-a-pl-sql-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!