Search code examples
oracle-databaseplsqlplsql-package

can we use default in a variable with function call in plsql?


I have a package, inside i declare g_suppress_all_xlog BOOLEAN := fnc_Suppress() DEFAULT NULL;

FUNCTION fnc_suppress
   RETURN BOOLEAN
IS
   v_ret       BOOLEAN := FALSE;                                  -- assume NO
   v_suppress  VARCHAR2 (3);
BEGIN
   SELECT VALUE
     INTO v_suppress
     FROM server_config
    WHERE name = 'Suppress_All_Xlog';

   IF (v_suppress = 'YES')
   THEN
      v_ret := TRUE;
   END IF;

   RETURN v_ret;
EXCEPTION
   WHEN OTHERS
   THEN
      prc_exception ();
END fnc_suppress;

I get error, how to default null and replace with the function value.


Solution

  • The fnc_suppress_in_pkg() can be in the package pkg_test. It just cannot be be used for assignment in the spec, it doesn't exist yet. It seems OP wants to initialize the variable g_suppress_all_xlog initialized before any function/procedure is executed. This can be accomplished with the initialization section of the package body. (Note: My playground has a table config_settings table available so I substituted that for server_config)

    create or replace package pkg_test as
        g_suppress_all_xlog boolean;
    
        procedure prc_exception;
        function fnc_suppress return boolean;
        -- Other procedure/functions declared here. 
    end  pkg_test;      
    
    create or replace package body pkg_test as
       procedure prc_exception is
       begin 
           null;
       end prc_exception;
    
       function fnc_suppress 
          return boolean
       is
          v_suppress  varchar2 (3);
       begin
          select setting
            into v_suppress
            from config_settings
           where name = 'Suppress_All_Xlog';
    
          return (v_suppress = 'YES');
       exception
          when others
          then
             prc_exception ();
       end fnc_suppress;
    
       -- Other procedure/functions defined here. 
    
    begin   -- this the package initialization. It executes 1 time when the package is first loaded.
      g_suppress_all_xlog := fnc_suppress;
    end pkg_test; 
    
    
    --  Test with direct reference to g_suppress_all_xlog 
        insert into config_settings(name,setting ) values('Suppress_All_Xlog', 'YES');
        declare
           setting varchar2(30); 
        begin
           if pkg_test.g_suppress_all_xlog 
              then dbms_output.put_line('Xlog being suppressed');
              else dbms_output.put_line('Xlog being written');
           end if;
        end; 
    

    IMHO>> However declaring the variable g_suppress_all_xlog is the spec is poor practice. That makes it accessible to any process in the same session for both read (not so bad) and write (bad). A better process would be to declare it in the body so it cannot be accessed directly. I understand it purpose is to having to select each time, so add another function to simply returns its value.