How to use a package constant in SQL SELECT statement?

后端 未结 4 693
难免孤独
难免孤独 2020-12-04 23:53

How can I use a package variable in a simple SELECT query statement in Oracle?

Something like

SELECT * FROM MyTable WHERE TypeId = MyPackage.MY_TYPE
         


        
4条回答
  •  [愿得一人]
    2020-12-05 00:07

    There is a more generic way which works fine for me. You create a function with input constant name (i.e. schema.package.constantname) and it returns you the constant value. You make use of executing immediate a PL/SQL block by binding res variable (see example).

    Function looks like this:

    CREATE OR REPLACE FUNCTION GETCONSTANTVALUE (i_constant IN VARCHAR2)  RETURN NUMBER deterministic AS
    
       res number; 
    BEGIN
    
       execute immediate 'begin :res := '||i_constant||'; end;' using out res;     
       RETURN res;
    
    END;
    /
    

    You can then use the constant of any package in any SQL, i.e. like

    select GETCONSTANTVALUE('PKGGLOBALCONSTANTS.constantname') from dual;
    

    Like this you need only 1 function and you take the advantage to use existing packages.constants.

提交回复
热议问题