Package variables vs procedure arguments

Is it better to use package-level variables inside package or to use procedure arguments?
I'm just asking because I have a bunch of parameters for each procedure (all of them are private, and are only called from within the package).
Is better this:
package a
is
--package variable
v_something my_table%rowtype;
procedure a
is
--do something with v_something
end;
procedure b
is
select * into v_something
from my_table
where rownum=1;
--call it without parameters
a;
end;
end;
or this:
package a
is
procedure a(inSomething my_table%rowtype)
is
--do something with v_something
end;
procedure b
v_something my_table%rowtype;
is
select * into v_something
from my_table
where rownum=1;
--call it with parameters
a(v_something);
end;
end;

Please post between the tags
..... and {code }
If you have multiple procedures updating and reusing the package variable you loose track of what value you have in the package variable.
And it depends what you are trying to do.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Variable number of arguments in procedure PL/SQL

    Hello everyone,
    I have a "simple" question : can a procedure PL/SQL take a variable number of arguments ?
    In my case, the procedure is called by the submit button of a form, and the form has variable number of inputs...
    Thanks you !

    862447 wrote:
    I have a "simple" question : can a procedure PL/SQL take a variable number of arguments ?No. Not in the style of Pascal and C/C++. E.g. int printf( char * format, … ) in C using va_list.
    In my case, the procedure is called by the submit button of a form, and the form has variable number of inputs...There are a couple of merhods.
    Code a fixed number of parameters in the procedure signature. Assign defaults to these. The caller can now select which parameters from the fixed list to use and which not.
    Create a structure. For example, having a 100 parameters in a signature is something I will call plain stupidity. This creates usability issues, maintenance issues and even performance issues. And debugging will be a nightmare. So instead create a structure (aka record in the PL/SQL language or an object using the SQL language) - where this structure describes (in a structured and logical way) the list of parameters.
    Neither of these method however allows the caller to pass a variable number parameters - the parameter signature is fixed. It has a fixed number of defined parameters.
    So the only way to simulate a variable parameter signature is to use a collection. The collection itself is of course a single parameter passed. But it can have 0 elements. It can have a 1000 elements. And similar to a va_list in C/C++, the procedure can iterate through the data passed via the parameter by the caller.
    Simple example:
    //-- define the collection type, e.g. a collection of strings
    create or replace type TStrings is table of varchar2(4000);The procedure's signature:
    --// passing by referencing and not value should be considered
    create or replace procedure FooProc( param TStrings ) is ..And to call this procedure with variable parameters:
    --// calling it with 2 param value
    FooProc( TString('123','testing') );
    --// calling it with 5 param values
    FooProc( TString('p1','p2','p3','p4','p5') );

  • Passing variable number of arguments in a stored procedure

    Hi Team,
    i am facing a problem. I have a dynamic form which contains some checkboxes. The number of checkboxes are dynamically generated on querying the database. On the form submission i want to call a stored procedure that will update the values in the database. i want to know that is there any way to handle variable number of arguments in the stored procedure or can i get the variables through some session context and use it in my stored procedure.
    Any help is greatly appreciated.
    Thanks&Regards
    Saurabh Jain

    Hi Saurabh,
    The method in which stored procedures are called on form submit is something as follows.
    Let us take your scenario of a form which has multiple checkboxes and a submit button. On clicking the submit button, this form data is submitted using either get or post. The form's submit action invokes a procedure.
    The HTML form code will look something like this..
    htp.formOpen( curl => 'URL /myProcedure',
    cmethod => 'post' );
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'A');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'B');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'C');
    htp.formSubmit( cname => 'myButton',
    cvalue => 'OK');
    Now, whenever the submit button is clicked, all these form values are passed to our stored procedure 'myProcedure'.
    "myProcedure" looks something like this.
    procedure myProcedure
    myCheckbox IN sys.owa_util.vc_arr,
    myButton IN VARCHAR2
    is
    begin
    end myProcedure;
    The point to be noted here is that the name of the variable being passed in the procedure is the same as the name of the HTML element being created in the HTML form. So, there is a direct mapping between the elements in the HTML form and the procedure parameters.
    Another noteworthy point is that since you have multiple checkboxes in your HTML form, it is impractical to name all the checkboxes differently and then pass those many parameters to your procedure (Imagine a scenario where there are a hundred check-boxes in an HTML form!). So portal allows you to give the same name (cname) to all the checkboxes in your HTML form, and if multiple checkboxes are checked, it will return all the checkbox values in an array (Note the usage of "myCheckbox IN sys.owa_util.vc_arr" in myProcedure).
    You can check out this link for more information.
    Re: retrieving data from fields
    Thanks,
    Ashish.

  • How to find Unused variables in procedure,function or package

    Hi all,
    I want find out unused variables in procedure, function and package.
    I have written below script for doing this ,but i am not getting the expected result.
    Kindly help me to improve the below code ,so that it works as expected.
    {code}
    version details
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    "CORE    11.2.0.3.0    Production"
    TNS for Linux: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    {code}
    {code}
    What i Have tried is This.
    DECLARE
      V_OBJECT_NAME VARCHAR2(30) :='PR_PRINT';
      V_OBJECT_TYPE VARCHAR2(30) :='PROCEDURE';
      CURSOR C1(CP_OBJECT_NAME VARCHAR2,CP_OBJECT_TYPE VARCHAR2)
      IS
        SELECT US.NAME,
          US.TYPE,
          US.LINE,
          REGEXP_SUBSTR(US.TEXT,'.* ') AS var_name
        FROM user_source US
        WHERE name=CP_OBJECT_NAME
        AND type  =CP_OBJECT_TYPE
        AND REGEXP_LIKE (TEXT,'(v_|g_|c_)','i')
        AND REGEXP_LIKE (TEXT,'^[^ ]')
        AND REGEXP_LIKE (TEXT,'^[^--]') ;
      v_count NUMBER ;
    BEGIN
      FOR i IN C1(V_OBJECT_NAME,V_OBJECT_TYPE)
      LOOP
        SELECT COUNT( *)
        INTO V_COUNT
        FROM USER_SOURCE US
        WHERE US.NAME=I.NAME
        AND REGEXP_LIKE(US.TEXT,i.var_name,'i' )
        AND US.LINE<>I.LINE;
        IF V_COUNT  =0 THEN
          DBMS_OUTPUT.PUT_LINE('variable '||I.VAR_NAME||'Is declared at line#'||I.LINE||' But no where used');
        END IF ;
      END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('p_err_code := '||SQLCODE||dbms_utility.format_Error_backtrace());
      DBMS_OUTPUT.PUT_LINE('p_err_msg := '||sqlerrm);
    END ;
    {code}
    Thanks,
    P Prakash

    Hello,
    as suggested by padders you can use PL/Scope, an example:
    ALTER SESSION SET PLSCOPE_SETTINGS='IDENTIFIERS:ALL';
    CREATE OR REPLACE PACKAGE ui_test1 AS
        global_number   NUMBER := 9;
    FUNCTION get_number
        RETURN NUMBER;
    END ui_test1;
    CREATE OR REPLACE PACKAGE BODY ui_test1 AS
    PROCEDURE setNull
         p_varchar          IN OUT VARCHAR2
    IS
    BEGIN
        p_varchar := NVL(p_varchar,'NULL');
    END setNull;
    FUNCTION get_number
        RETURN NUMBER
    IS
        FUNCTION setZero
             p_number       IN NUMBER
            RETURN NUMBER
        IS
        BEGIN
            RETURN NVL(p_number,0);
        END setZero;
    BEGIN
        RETURN global_number;
    END get_number;
    END ui_test1;
    SELECT  DISTINCT
            object_name
           ,object_type
           ,name
           ,type
           ,line
           ,col
    FROM    all_identifiers obj
    WHERE   obj.owner = USER
    AND     obj.usage = 'DECLARATION'
    AND     obj.object_name = 'UI_TEST1'
    AND     NOT EXISTS (
                SELECT  1
                FROM    all_identifiers with_rh
                WHERE   obj.signature = with_rh.signature
                AND     with_rh.usage IN ('REFERENCE','CALL','ASSIGNMENT')
    ORDER BY TYPE
            ,object_name
            ,object_type
            ,name;
    OBJECT_NAME  OBJECT_TYPE   NAME       TYPE       LINE COL
    UI_TEST1     PACKAGE       GET_NUMBER FUNCTION     11  10
    UI_TEST1     PACKAGE BODY  SETZERO    FUNCTION     35  14
    UI_TEST1     PACKAGE       UI_TEST1   PACKAGE       1   9
    UI_TEST1     PACKAGE BODY  SETNULL    PROCEDURE    12  11
    Regards
    Marcus

  • Accessing a packaged variable through db link

    How do I access a packaged variable remotely? (Syntax)

    You cannot do that:
    SQL> conn xx/xx@xx
    Connected.
    SQL> create package p is
      2   a number;
      3  end;
      4  /
    Package created.
    SQL> conn yy/yy@yy
    Connected.
    SQL> desc p@yy
    SQL> set serveroutput on
    SQL> create synonym p1 for p@xx;
    Synonym created.
    SQL> desc p1;
    SQL> begin
      2    p1.a := 1;
      3    dbms_output.put_line(p.a);
      4  end;
      5  /
      p1.a := 1;
    ERROR at line 2:
    ORA-06550: line 2, column 6:
    PLS-00512: Implementation Restriction: 'P1.A': Cannot directly access remote package variable or cursor
    ORA-06550: line 2, column 3:
    PL/SQL: Statement ignoredInstead you should access these variables via functions and/or procedures. In following example I've created the private variable in package p but this doesn't matter whether it is private or public.
    SQL> conn xx/xx@xx
    SQL> create or replace package p is
    2 procedure set_a (v in number);
    3 function get_a return number;
    4 end;
    5 /
    Package created.
    SQL> ed
    Wrote file afiedt.buf
    1 create or replace package body p is
    2 a number;
    3 procedure set_a (v in number) is
    4 begin
    5 a := v;
    6 end;
    7 function get_a return number is
    8 begin
    9 return a;
    10 end;
    11* end;
    SQL> /
    Package body created.
    SQL> conn yy/yy@yy
    Connected.
    SQL> set serveroutput on
    SQL> desc p1
    FUNCTION GET_A RETURNS NUMBER
    PROCEDURE SET_A
    Argument Name Type In/Out Default?
    V NUMBER IN
    SQL> ed
    Wrote file afiedt.buf
    1 begin
    2 p1.set_a(1);
    3 dbms_output.put_line(p1.get_a);
    4* end;
    SQL> /
    1
    PL/SQL procedure successfully completed.
    Gints Plivna
    http://www.gplivna.eu

  • How to get values from a stored package variable of type record ?

    Sir,
    In my JClient form, I need to get values from a database stored package variable of type record. And the values are retained in the JClient form for the whole session. The values are copied only once when the form is started.
    What is the best way to do that ?
    Thanks
    Stephen

    Stephen,
    not sure what your model is, but if it is Business Components, I think I would expose the properties as a client method on the application module. This way all JClient panels and frames will have access to it. You could use a HashMap to store the data in teh app module.
    If JDBC supports the record type, then you should be able to call it via a prepared SQL statement. If not, you may consider writing a PLSQL accessor to your stored procedure that returns something that can be handled.
    Steve Muench provides the following examples on his blog page
    http://otn.oracle.com/products/jdev/tips/muench/stprocnondbblock/PassUserEnteredValuesToStoredProc.zip
    http://otn.oracle.com/products/jdev/tips/muench/multilevelstproc/MultilevelStoredProcExample.zip
    Frank

  • BC4J ApplicationModule Pooling and persitent package variables

    Scenario:
    HttpRequest
    starts=> - use SessionCookie API to get an Application Module
    - call pck.set_id (packaged procedure which sets i++ )
    - call pck.get_id (packaged function returning value of i)
    finish=> release application Module (***)
    What I've seen:
    (***) When release statelessly
    Two browser sessions (could) get the same Application Module, in which case the 'i' value is incremented 'by' both browser sessions.
    (***) When release statefully
    Two browser sessions get their 'own' Application Module and manipulate their own 'i' value (even) between consequitive HTTP Requests.
    If both situations are explained and viewed correctly, does BC4J application module pooling guarantee that whenever I want to use an AM statefully I get persistent package variable state reproduced in that AM???
    If I understand correctly this doesn't mean I get the 'same' AM instance each time, but the BC4J Application Module pooling makes sure that whichever AM I get has state reproduced?
    Thx for explaining/affirming?
    -J.

    Scenario:
    HttpRequest
    starts=> - use SessionCookie API to get an Application Module
    - call pck.set_id (packaged procedure which sets i++ )
    - call pck.get_id (packaged function returning value of i)
    finish=> release application Module (***)
    What I've seen:
    (***) When release statelessly
    Two browser sessions (could) get the same Application Module, in which case the 'i' value is incremented 'by' both
    browser sessions.
    (***) When release statefully
    Two browser sessions get their 'own' Application Module and manipulate their own 'i' value (even) between
    consequitive HTTP Requests.
    If both situations are explained and viewed correctly, does BC4J application module pooling guarantee that whenever
    I want to use an AM statefully I get persistent package variable state reproduced in that AM???In scenario2 above the reason that two different ApplicationModule instances are returned for each
    respective session is that the pool has not yet hit its recycle threshold. Once this threshold is hit then the pool will
    begin "recycling" the state managed instances and you will observe the same behaviour as in scenario 1.
    If I understand correctly this doesn't mean I get the 'same' AM instance each time, but the BC4J Application Module
    pooling makes sure that whichever AM I get has state reproduced?This is true for the state that BC4J is aware of (i.e. iterator state, pending transactional changes, etc).
    However, BC4J cannot reproduce user state, like the PL/SQL session state that you have defined above. In order
    to maintain "user" state it is necessary to:
    1. passivate/activate the user state when BC4J passivates/activates its own state. BC4J currently provides a hook for
    this via ApplicationModuleImpl.passivateState(Document, Element) and ApplicationModuleImpl.activateState(Element).
    2. reset user state when BC4J recycles an ApplicationModule. 9.0.2 does not define a great mechanism for
    resetting user state. However, the upcoming maintenance release will provide an ApplicationModuleImpl.reset
    hook to clean up session state properly when an ApplicationModule is recycled.
    Hope this helps.

  • Forms 10 and PL/SQL: Using a server package variable

    Hi,
    I have a variable created at package level in the server,
    When I try to assign its value to a Forms item, I get an error.
    "Unable to access distant package variable".
    What should I do to access this variable?
    Many thanks

    Hello,
    Add to the package a procedure to set this variable, and also a function that returns the variable content.
    Francois

  • Accessing database package variables from Forms

    I have a database package that populates a table of values, i.e.
    type t_route_list is table of rt_route.RTR_ID%type;
    route_list t_route_list
    route_list gets populated by a package function and I want to access route_list in the Form.
    While I can access other package variables by writing a function that returns the variable, Forms doesnt seem to like functions that return a user defined datatype as above. I have also tried using a procedure with an OUT param instead of a function but it also fails with same error.
    i.e.
    declare
    v_route_list pkg_bulk_route_replace.t_route_list;
    begin
    pkg_bulk_route_replace.init;
    pkg_bulk_route_replace.get_route_list(v_route_list);
    message(v_route_list(1));
    end;
    This will not compile, but removing the index (1) from the last line makes it compile but crash with ORA-0600.
    The code above with message replaced with dbms_out.put_line works fine on TOAD.
    So my question is......
    Can my database package return a plsql table to a form and if so, how?!

    Actually I've got this to work now!
    Thde main culprit appears to be a difference in the version of sql or pl/sql used on forms (version 5) and the database (8.1.7).
    I had defined my table as a nested table. By redefining this as a indexed table, simply by adding on 'index by binary_integer' on my server package, I am suddenly able to access the elements of the table on my form. Fortunately this did not break the server code either - the table was populated using bulk collect and that still works.
    Still got a bit of coding to do, but things are looking up now.

  • Global Variables Vs Form Library Package Variables Vs DB Package Variables

    I realise this question has been asked a few times with varying degrees of answers, but I am still seeking comment/advice from others.
    I am aware of following options for retaining persistent data to share between forms.
    1. Package variables in a library that you share in a session.
    This requires usage of SHARE_LIBRARY_DATA, there is risk that this not set, then does not share data.
    2. Package variables in a database package.
    Requires round trip to DB. Is this expensive for performance?
    What about risk of DB package becoming invalid and losing state?
    3. Use global variables
    Can be tricky to manage.
    4. Use parameters
    Only one way, ie called form cannot alter value that caller can see.
    Packages are closest to OO approach in using get and set modules. Allows all variables to be managed in one location. This appears best practice.
    Forms library packages appear risky if caller does not include SHARE_LIBRARY_DATA.
    DB packages have cost of round trip to DB. Does this become expensive is have to reference many times. Also topic of DB package becoming invalid and losing state?
    Forms global variables have regular disadvantages of globals, ie not sure who may modify. Need to manage carefully. Text only
    As a second related question, for value such as current user, for performance (and maintainability) is it better to obtain this from oracle user function each time, or save somewhere (in one of options above) and use that saved value each time.

    My personal opinion:
    I like the "packaged" version with getters and setters. In general, i create a client-side package in a pll which has methods to access the value by getters and setters. With that, the "implementation" is encapsulated and doesn't really matter to the rest of your system. All modules have to access the value using the getter and setter.
    Inside the procedure i use two approaches:
    1. If its for communication purposes between different forms i use globals, which are filled or extracted in the getter and setter (see this http://andreas.weiden.orcl.over-blog.de/article-28180655.html )
    2. If its for someother purpose where the value should be "session persistent" i use a database package with getters and setters, which are called from the client-side package getter and setter. If the value is quite "constant" throughout the session, i read the value once at initialization code of the client-side package and the getter just returns that "cached" value
    Hope this helps.

  • Referencing Package Variables

    Running Forms 6i and Oracle 8.1.6
    Can you reference server side package variables directly from Forms, or do you still have to write a wrapper procedures to "set" and "get" them.
    CREATE OR REPLACE package test_pkg as
    v_pkgvar varchar2(10) := 'TEST';
    TYPE r_emp_rec IS RECORD
    (empno emp.empno%TYPE,
         ename emp.ename%TYPE,
         mgr emp.mgr%TYPE,
         deptno emp.deptno%TYPE,
         dname dept.dname%TYPE,
         loc dept.loc%TYPE
    TYPE t_emp_rec IS TABLE OF r_emp_rec INDEX BY BINARY_INTEGER;
    end;
    DECLARE
    data_blk test_pkg.t_emp_rec;
    v_test varchar2(100) := test_pkg.v_pkg_var;
    BEGIN
    null;
    END;
    It seems funny that i can reference test_pkg.t_emp_rec;
    but not test_pkg.v_pkg_var;
    Thanks for your help

    You have to use wrapper setters and getters to reference package variables on Server side PL/SQL from client side PL/SQL (Forms) this will not change no matter what the versions concerned

  • Global package variable for the current rendering item

    I like to define a generic plsql function which handles all the page 0 item conditions. I will place this function call in all page 0 item conditions.
    Now I need a global (htmldb_application) package variable which I can use to identify for which item condition the function is executed.
    Which global variable can I use for this purpose or is there an other way to do this.
    I dont't want to give the the item names hardcode as argument of the function.

    Scott,
    I will try to clarify my question.
    I have lot of page 0 items.
    I like to give every item the same plsql condition such as htmldb_pck.show_item or
    htmldb_pck.show_item('#CURRENT_ITEM#').
    In my own htmldb_pck.show_item function I have all the display coding of the generic items.
    My problem is that I have to know from which item the function is called.
    Thanks,
    Fred.
    May be this is something for an enhancement. Not only for the items, but also for the buttons, tabs, tab sets and report columns. So you know in generic pl/sql from which object the pl/sql is called.

  • Unable to refer package variable outside package

    Why am I unable to refer package variable defined in its spec outside in blow example?
    =================================================
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.3.0 - Production
    SQL> create or replace package xx_my_package is
    2 x VARCHAR2(10):='ABC';
    3 end xx_my_package;
    4 /
    Package created.
    SQL> select xx_my_package.x from dual;
    select xx_my_package.x from dual
    ERROR at line 1:
    ORA-06553: PLS-221: 'X' is not a procedure or is undefined
    SQL>
    ===============================================

    We cannot use PL/SQL variables in SQL ... unless we use that SQL inside a PL/SQL block:
    SQL> create or replace package xx_my_package is
      2    x VARCHAR2(10):='ABC';
      3  end xx_my_package;
      4  /
    Package created.
    SQL> select xx_my_package.x from dual
      2  /
    select xx_my_package.x from dual
    ERROR at line 1:
    ORA-06553: PLS-221: 'X' is not a procedure or is undefined
    SQL> create or replace function get_x return varchar2
      2  as
      3    rv varchar2(10);
      4  begin
      5    select  xx_my_package.x
      6    into rv
      7    from dual;
      8    return rv;
      9  end;
    10  /
    Function created.
    SQL> select get_x from dual
      2  /
    GET_X
    ABC
    SQL> Cheers, APC

  • Package variables urgent

    Hi,
    I want to use certain variables which have been declared in the package ie global variables .
    These variables are to be accessed in a trigger.
    how do i do this.
    any method is welcome,either through functions or procedures.
    please do provide the solution

    Thanks both for the reply.
    Now the scenario has changed a bit.
    what i have done is that i have defined a package variable in the package.
    Now The package has 4 sps and i function.
    I assign a value to the package variable in one of the sps.
    using this value, I insert it into a temporary which i create inside the sp.(using execute immediate)
    can i do this.i get an error of previalges which was sorted out.
    Now i am accesiing the data in the temp table inside the function.the function returns me an id which is retrieved from another table using the value in the temp table.
    This function is called inside a trigger,which gives me an error ora-04601-existing state of package being discarded.
    pls help.

  • Packaged Variables

    Is it possible to create a variable that is read only and global to multiple programs/apps, and yet can be modified from only one specific package?
    Thanks for any help.

    <Can you please provide me with a simple example of how this could be done.>
    Something like this (untested)
    create or replace package foo is
      private_global_variable pls_integer;
      --public procedure to change variable value
      procedure change_var (p_value pls_integer) is
      begin
        private_global_variable := p_value;
      end;
      --public procedure to see variable value
      function get_value return pls_integer is
      begin
        return private_global_variable;
      end;
    ...

Maybe you are looking for

  • AT305-T16 isn't recognized by Windows XP

    When connected my AT305 tablet to my Windows XP PC, I get a dialog saying that new hardware has been found and software must be installed. But I have no drivers to install and Windows can't find one. So the PC never recognizes the tablet. Any suggest

  • Error in Receiving Transaction Processor concurrent program

    Hi all,i am trying to insert data into rcv_headers_interface and rcv_transactions_interface.So,for this data to get populated in rcv_shipment_headers and rcv_shipment_lines i am running Receiving Transaction Processor concurrent program in purchasing

  • Payment terms / Due date Schedule

    Dear experts, how do the Payment terms definen in FI - FICA, relate to the Due Date Schedule used in Student Lifecycle Management?. Do I define Payment terms for the contract account, or just the Due Date Schedule? Best regards.

  • How to make an object mutable?

    Can any one tell me how to make an object mutable? Following is Class X & Y? class Y public static void main(String arg[]) { X a1=new X(); Object a=a1.get(); System.out.println(a.toString()); a1.set(a); System.out.println(a.toString()); class X imple

  • Firefox promps at every start for an update to 6.0 but I already have 6.o installed?

    Win 7