DBMS_JOB using Packaged Functions but Package goes invalid

Is there any way to check a package while running a PL/SQL procedure to see if it's state is valid and then catch the exception?
In my case usually just calling any function in the package 1x clears it up but the procedure in question runs as a DBMS_JOB it just keeps failing. This procedure could run often enough that Oracle will mark it as broken but I want to give it every shot at execution on time instead of having to make it wait till the next cycle.
What I would like to do is to catch the exception for the package state being invalid and basically have it go back to the beginning of the procedure and give it another try before failing in case it is just a failure because the package has been altered.
Is there any way to do this?

Firstly, I'll copy/paste my standard response regarding package state going invalid as it usually helps to have an understanding of these things...
Packages tend to fail because of their "package state". A package has a "state" when it contains package level variables/constants etc. and the package is called. Upon first calling the package, the "state" is created in memory to hold the values of those variables etc. If an object that the package depends upon e.g. a table is altered in some way e.g. dropped and recreated, then because of the database dependencies, the package takes on an INVALID status. When you next make a call to the package, Oracle looks at the status and sees that it is invalid, then determines that the package has a "state". Because something has altered that the package depended upon, the state is taken as being out of date and is discarded, thus causing the "Package state has been discarded" error message.
If a package does not have package level variables etc. i.e. the "state" then, taking the same example above, the package takes on an INVALID status, but when you next make a call to the package, Oracle sees it as Invalid, but knows that there is no "state" attached to it, and so is able to recompile the package automatically and then carry on execution without causing any error messages. The only exception here is if the thing that the package was dependant on has changes in such a way that the package cannot compile, in which case you'll get an Invalid package type of error.
And if you want to know how to prevent discarded package states....
Move all constants and variables into a stand-alone package spec and reference those from your initial package. Thus when the status of your original package is invlidated for whatever reason, it has no package state and can be recompiled automatically, however the package containing the vars/const will not become invalidated as it has no dependencies, so the state that is in memory for that package will remain and can continue to be used.
As for having package level cursors, you'll need to make these local to the procedures/functions using them as you won't be able to reference cursors across packages like that (not sure about using REF CURSORS though.... there's one for me to investigate!)
This first example shows the package state being invalided by the addition of a new column on the table, and causing it to give a "Package state discarded" error...
SQL> set serveroutput on
SQL>
SQL> create table dependonme (x number)
  2  /
Table created.
SQL>
SQL> insert into dependonme values (5)
  2  /
1 row created.
SQL>
SQL> create or replace package mypkg is
  2    procedure myproc;
  3  end mypkg;
  4  /
Package created.
SQL>
SQL> create or replace package body mypkg is
  2    v_statevar number := 5; -- this means my package has a state
  3
  4    procedure myproc is
  5      myval number;
  6    begin
  7      select x
  8      into myval
  9      from dependonme;
10
11      myval := myval * v_statevar;
12      DBMS_OUTPUT.PUT_LINE('My Result is: '||myval);
13    end;
14  end mypkg;
15  /
Package body created.
SQL>
SQL> exec mypkg.myproc
My Result is: 25
PL/SQL procedure successfully completed.
SQL>
SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
  2  /
OBJECT_NAME
OBJECT_TYPE         STATUS
MYPKG
PACKAGE             VALID
MYPKG
PACKAGE BODY        VALID
SQL>
SQL>
SQL> alter table dependonme add (y number)
  2  /
Table altered.
SQL>
SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
  2  /
OBJECT_NAME
OBJECT_TYPE         STATUS
MYPKG
PACKAGE             VALID
MYPKG
PACKAGE BODY        INVALID
SQL>
SQL> exec mypkg.myproc
BEGIN mypkg.myproc; END;
ERROR at line 1:
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "SCOTT.MYPKG" has been invalidated
ORA-06508: PL/SQL: could not find program unit being called: "SCOTT.MYPKG"
ORA-06512: at line 1
SQL>
SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
  2  /
OBJECT_NAME
OBJECT_TYPE         STATUS
MYPKG
PACKAGE             VALID
MYPKG
PACKAGE BODY        INVALID
SQL>
SQL> exec mypkg.myproc
PL/SQL procedure successfully completed.
SQL>
SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
  2  /
OBJECT_NAME
OBJECT_TYPE         STATUS
MYPKG
PACKAGE             VALID
MYPKG
PACKAGE BODY        VALIDAnd this next example shows how having the package variables in their own package spec, allows the package to automatically recompile when it is called even though it became invalidated by the action of adding a column to the table.
SQL> drop table dependonme
  2  /
Table dropped.
SQL>
SQL> drop package mypkg
  2  /
Package dropped.
SQL>
SQL> set serveroutput on
SQL>
SQL> create table dependonme (x number)
  2  /
Table created.
SQL>
SQL> insert into dependonme values (5)
  2  /
1 row created.
SQL>
SQL> create or replace package mypkg is
  2    procedure myproc;
  3  end mypkg;
  4  /
Package created.
SQL>
SQL> create or replace package mypkg_state is
  2    v_statevar number := 5; -- package state in seperate package spec
  3  end mypkg_state;
  4  /
Package created.
SQL>
SQL> create or replace package body mypkg is
  2    -- this package has no state area
  3
  4    procedure myproc is
  5      myval number;
  6    begin
  7      select x
  8      into myval
  9      from dependonme;
10
11      myval := myval * mypkg_state.v_statevar;  -- note: references the mypkg_state package
12      DBMS_OUTPUT.PUT_LINE('My Result is: '||myval);
13    end;
14  end mypkg;
15  /
Package body created.
SQL>
SQL> exec mypkg.myproc
My Result is: 25
PL/SQL procedure successfully completed.
SQL>
SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
  2  /
OBJECT_NAME
OBJECT_TYPE         STATUS
MYPKG
PACKAGE             VALID
MYPKG
PACKAGE BODY        VALID
SQL>
SQL> alter table dependonme add (y number)
  2  /
Table altered.
SQL>
SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
  2  /
OBJECT_NAME
OBJECT_TYPE         STATUS
MYPKG
PACKAGE             VALID
MYPKG
PACKAGE BODY        INVALID
SQL>
SQL> exec mypkg.myproc
My Result is: 25
PL/SQL procedure successfully completed.---------------------------------------------------------------------------------------------
Secondly, from this above standard response, you can see how to check for package state if you want to determine it programatically.
;)

Similar Messages

  • Using lookup function but to show multiple returns?

    Okay so I have been talked through how to use a lookup function to show which student in my class has scored the highest grade.  The formula used displays there name in one column and the score they achieved in another column which I have set up in a small seperate table.  However as suggested in my intial lookup function search it was suggested that I would encounter a problem if two students both achieved the same highest score.  However in the results table I have created it only shows one student.  Is it possible to have a function or formula that will simply show the top scores and the students that scored it when they are tied? 
    Thanks
    Marcus

    The easiest way to accomplish this, Marcus, is by simply sorting all rows by grade.  Sure, you can click on the column tab and hit "sort ascending", but I'm guessing you want something a little more dynamic than that.
    So I've set up a class of 20 students and gave them all random grades btwn 40 - 99.  (That's how it was done when I was in high school.  )  I added a third column which takes that grade, multiplies it by 1000, and adds the row number of the student.  This creates a unique identifier based on a possibly-non-unique grade:
    Now it's simply a matter of using the LARGE function to rank these new identifiers, and then using LOOKUP to get the actual grade and name for that identifier.  (Note that the grades changed; changing the focus from one cell to another creates new random values for the grades.)
    The formula for columns b and c for this Ranking table are standard Lookup functions:
    =LOOKUP($A1,Grades :: $C,Grades :: $B) to get the grades  ($A2 for 2nd column, etc.), and
    =LOOKUP($A1,Grades :: $C,Grades :: $A) to get the names.
    I'd suggest hiding these identifier columns.
    Now, to limit this display to the "X" highest grades, I'm going to continue this into another reply.
    Vince

  • TS1367 I am asking this question about my 27 inch iMac Desktop Computer. I normally use my Laptop and very seldom use the desktop but was going to download the new software earlier today. I could not wake it from sleep.

    The other evening we had a storm and lightening hit a house a few doors from me. It jolted my chair but that seemed to be all here. I use my laptop most of the time but since there was a software download I went to my 27 inch iMac and could not wake it from sleep. The light on the keyboard is not lit either. I have this connected to a Battery Backup Power so do not know what has happened or what to do. When I push the power button to try to turn it on nothing happens. There is no shound, no video, nothing; however the disk drive that does my time maching backup has a light on it and the other things that are plugged into the battery power pack also have lights on them. The printer is on and says it is ready to print. Since I cannot boot it up I do not know what to do to even try to get it started. I did not know what would happen if I put the first start up disk in  the external disk drive and try that or not. The internal drive is broken. I do not have any repair shops or apple stores around me at all less than 150 miles away and I am disabled with 24/7 help and oxygen so can not take it in. Are there any suggestions that anyone can give me. I have not been able to find any way to reset the backup battery pack either. It is a Tripp-Lite. Any help anyone can give will be greatly appreciated. Thanking you in advance for your time and trouble.
    Jean

    The other evening we had a storm and lightening hit a house a few doors from me. It jolted my chair but that seemed to be all here. I use my laptop most of the time but since there was a software download I went to my 27 inch iMac and could not wake it from sleep. The light on the keyboard is not lit either. I have this connected to a Battery Backup Power so do not know what has happened or what to do. When I push the power button to try to turn it on nothing happens. There is no shound, no video, nothing; however the disk drive that does my time maching backup has a light on it and the other things that are plugged into the battery power pack also have lights on them. The printer is on and says it is ready to print. Since I cannot boot it up I do not know what to do to even try to get it started. I did not know what would happen if I put the first start up disk in  the external disk drive and try that or not. The internal drive is broken. I do not have any repair shops or apple stores around me at all less than 150 miles away and I am disabled with 24/7 help and oxygen so can not take it in. Are there any suggestions that anyone can give me. I have not been able to find any way to reset the backup battery pack either. It is a Tripp-Lite. Any help anyone can give will be greatly appreciated. Thanking you in advance for your time and trouble.
    Jean

  • I am not sure how to use this site but here goes nothing, I recently lost my Iphone and dont have the App to locate it. is there some other way to lock the phone with a serial number?

    I need help locating or locking my Iphone its been stolen.

    No.
    The only way would be if you had turned on the find my iphone feature in the iphone settings.
    The app that you download has nothing to do with it.  The feature is bult in.
    If you did not turn it on, then you can do nothing, but report it to the police and your carrier, and change your passwords.
    Sorry

  • 2.1.0.62: Problem with Package.Functions and Unit Tests

    I like the new Sqldeveloper - I startet trying Unit Tests as described here: Link: [http://www.oracle.com/technology/obe/11gr2_db_prod/appdev/sqldev/sqldev_unit_test/sqldev_unit_test.htm#t4]
    It worked with a test-procedure. Now i am trying to test my package functions, but all i get is this:
    Die folgende Prozedur wurde ausgeführt.
    Ausführungsaufruf
    BEGIN
    :1 := "PKG_MYPACK"."CREATEFUNCTION"(IN_PROGRAMMEID=>:2,
    IN_AMOUNT=>:3,
    IN_SWS=>:4);
    END;
    Bind-Variablen verwendet
    1 INTEGER OUT (null)
    2 INTEGER IN 1
    3 INTEGER IN 10
    4 INTEGER IN 11
    Ausführungsergebnisse
    ERROR
    Ungültige Konvertierung angefordert
    oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:110)
    oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:171)
    oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:227)
    oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:439)
    oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:7723)
    oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7496)
    oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7978)
    oracle.jdbc.driver.OracleCallableStatement.setObject(OracleCallableStatement.java:4063)
    oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:221)
    oracle.dbtools.raptor.datatypes.strategies.callablestatement.CallableBindingDatum.customBindIN(CallableBindingDatum.java:135)
    oracle. ...
    what can i do?

    Created
    Bug 8976245 - EA1: UNIT_TEST: INVALID CONVERSION ERROR USING INTEGER PARAMETER
    and have asked bug responder to keep you updated on status here in the forum.
    Bad news is that any INTEGER parameter for which you specify a non-null value will fail.
    Possibly helpful news is that if you create a 'clone' of you function using NUMBER as the data type, you can continue to experiment with how unit testing may be of use to you.
    Sorry no instant answer. :(
    Brian
    SQL Developer Team

  • Oracle Package Function

    hello,
    I have written a package function but I cannot call it from .net environment correctly.
    I want to ask you that is there anything wrong in the package:
    Specification Part:
    CREATE OR REPLACE PACKAGE SAGECM AS
    TYPE T_CURSOR IS REF CURSOR;
    FUNCTION COUNTREQ
    p_ID IN VARCHAR2,
    p_version IN VARCHAR2,
    num_of_req OUT NUMBER
    RETURN NUMBER;
    END SAGECM;
    Body Part:
    CREATE OR REPLACE PACKAGE BODY SAGECM AS
    FUNCTION COUNTREQ
    p_ID IN VARCHAR2,
    p_version IN VARCHAR2,
    num_of_req OUT NUMBER
    RETURN NUMBER
    IS
    BEGIN
    SELECT count(*) INTO num_of_req FROM SAGECM_REQ WHERE ID=p_ID AND Version=p_version;
    return num_of_req;
    END COUNTREQ;
    END SAGECM;

    is there anything wrong in the packageYes. You are attempting to RETURN an OUT parameter. This is bad. I suspect you don't understand the difference between a procedure and a function....
    CREATE OR REPLACE PACKAGE SAGECM AS
    TYPE T_CURSOR IS REF CURSOR;
    FUNCTION COUNTREQ
    p_ID IN VARCHAR2,
    p_version IN VARCHAR2
    RETURN NUMBER;
    PROCEDURE COUNTREQ
    p_ID IN VARCHAR2,
    p_version IN VARCHAR2,
    num_of_req OUT NUMBER
    END SAGECM;
    CREATE OR REPLACE PACKAGE BODY SAGECM AS
      FUNCTION COUNTREQ
          p_ID IN VARCHAR2,
          p_version IN VARCHAR2
        RETURN NUMBER
      IS
        return_value NUMBER;
      BEGIN
        SELECT count(*) INTO return_value
        FROM SAGECM_REQ
        WHERE ID=p_ID AND Version=p_version;
        RETURN return_value;
      END COUNTREQ;
      PROCEDURE COUNTREQ
          p_ID IN VARCHAR2,
          p_version IN VARCHAR2,
          num_of_req OUT NUMBER
        ) IS
      BEGIN
        num_of_req := COUNTREQ(p_ID,p_version);
      END COUNTREQ;
    END SAGECM;
    /Note: the above is for illutrative purposes only and is not intended as an example of good programming practice!
    Find out more in the docs!
    Cheers, APC

  • Pipelined function in package example 11g

    Hi all,
    could you please show me example of using pipelined function in package with my sample data?
    My need is to return the following data using pipelined function in package:
    select 1 as t, 2 as y, 'u' as j, trunc(sysdate-1) as k from dual union all
    select 3 as t, 4 as y, 'h' as j, trunc(sysdate-2) as k from dual Thanks ahead.

    p.s. if your problem is that you're not sure how to pipe multiple columns, take a look at this example (from my library of standard examples)...
    SQL> CREATE OR REPLACE TYPE myemp AS OBJECT
      2  ( empno    number,
      3    ename    varchar2(10),
      4    job      varchar2(10),
      5    mgr      number,
      6    hiredate date,
      7    sal      number,
      8    comm     number,
      9    deptno   number
    10  )
    11  /
    Type created.
    SQL> CREATE OR REPLACE TYPE myrectable AS TABLE OF myemp
      2  /
    Type created.
    SQL> CREATE OR REPLACE FUNCTION pipedata(p_min_row number, p_max_row number) RETURN myrectable PIPELINED IS
      2    v_obj myemp := myemp(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
      3  BEGIN
      4    FOR e IN (select *
      5              from (
      6                    select e.*
      7                          ,rownum rn
      8                    from (select * from emp order by empno) e
      9                   )
    10              where rn between p_min_row and p_max_row)
    11    LOOP
    12      v_obj.empno    := e.empno;
    13      v_obj.ename    := e.ename;
    14      v_obj.job      := e.job;
    15      v_obj.mgr      := e.mgr;
    16      v_obj.hiredate := e.hiredate;
    17      v_obj.sal      := e.sal;
    18      v_obj.comm     := e.comm;
    19      v_obj.deptno   := e.deptno;
    20      PIPE ROW (v_obj);
    21    END LOOP;
    22    RETURN;
    23  END;
    24  /
    Function created.
    SQL> select * from table(pipedata(1,5));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7369 SMITH      CLERK            7902 17-DEC-1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN         7698 20-FEB-1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN         7698 22-FEB-1981 00:00:00       1250        500         30
          7566 JONES      MANAGER          7839 02-APR-1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN         7698 28-SEP-1981 00:00:00       1250       1400         30
    SQL> select * from table(pipedata(6,10));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7698 BLAKE      MANAGER          7839 01-MAY-1981 00:00:00       2850                    30
          7782 CLARK      MANAGER          7839 09-JUN-1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST          7566 19-APR-1987 00:00:00       3000                    20
          7839 KING       PRESIDENT             17-NOV-1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN         7698 08-SEP-1981 00:00:00       1500          0         30
    SQL> select * from table(pipedata(11,15));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7876 ADAMS      CLERK            7788 23-MAY-1987 00:00:00       1100                    20
          7900 JAMES      CLERK            7698 03-DEC-1981 00:00:00        950                    30
          7902 FORD       ANALYST          7566 03-DEC-1981 00:00:00       3000                    20
          7934 MILLER     CLERK            7782 23-JAN-1982 00:00:00       1300                    10
    SQL>

  • Returning Collection using table function

    Hi,
    I'm trying to return a collection with record type using table function but facing some issues.
    Could someone help me with it.
    SUNNY@11gR1> create or replace package test_pack as
      2  type rec_typ is record (
      3  empname varchar2(30),
      4  empage number(2),
      5  empsal number(10));
      6  type nest_typ is table of rec_typ;
      7  function list_emp return nest_typ;
      8  end;
      9  /
    Package created.
    Elapsed: 00:00:00.01
    SUNNY@11gR1> create or replace package body test_pack is
      2  function list_emp return nest_typ is
      3  nest_var nest_typ := nest_typ();
      4  begin
      5  nest_var.extend;
      6  nest_var(nest_var.last).empname := 'KING';
      7  nest_var(nest_var.last).empage := 25;
      8  nest_var(nest_var.last).empsal := 2500;
      9  nest_var.extend;
    10  nest_var(nest_var.last).empname := 'SCOTT';
    11  nest_var(nest_var.last).empage := 22;
    12  nest_var(nest_var.last).empsal := 3500;
    13  nest_var.extend;
    14  nest_var(nest_var.last).empname := 'BLAKE';
    15  nest_var(nest_var.last).empage := 1;
    16  return nest_var;
    17  end;
    18  end;
    19  /
    Package body created.
    Elapsed: 00:00:00.01
    SUNNY@11gR1> select * from table(test_pack.list_emp);
    select * from table(test_pack.list_emp)
    ERROR at line 1:
    ORA-00902: invalid datatype
    Elapsed: 00:00:00.01
    SUNNY@11gR1>Regards,
    Sunny

    But if I use pipelined function instead then I'm able to retrieve the records
    SUNNY@11gR1> create or replace package test_pack as
      2  type rec_typ is record (
      3  empname varchar2(30),
      4  empage number(2),
      5  empsal number(10));
      6  type nest_typ is table of rec_typ;
      7  function list_emp return nest_typ pipelined;
      8  end;
      9  /
    Package created.
    SUNNY@11gR1> ed
    Wrote file afiedt.buf
      1  create or replace package body test_pack as
      2  function list_emp return nest_typ pipelined is
      3  rec_var rec_typ;
      4  begin
      5  rec_var.empname := 'KING';
      6  rec_var.empage := 24;
      7  rec_var.empsal := 10000;
      8  pipe row(rec_var);
      9  rec_var.empname:='SCOTT';
    10  rec_var.empage:=22;
    11  rec_var.empsal:=2000;
    12  pipe row(rec_var);
    13  rec_var.empname:='BLAKE';
    14  rec_var.empage:='1';
    15  pipe row(rec_var);
    16  return;
    17  end;
    18* end;
    SUNNY@11gR1> /
    Package body created.
    Elapsed: 00:00:00.01
    SUNNY@11gR1> select * from table(test_pack.list_emp);
    EMPNAME                            EMPAGE     EMPSAL
    KING                                   24      10000
    SCOTT                                  22       2000
    BLAKE                                   1       2000
    Elapsed: 00:00:00.00Why is that?
    Regards,
    Sunny

  • How to use DECODE function in Exspression?

    Hi,
    Can we use DECODE in Expression?
    I'm trying to use DECODE function but there is an error during the validation. But when i validate the mapping, it is successfully compiled but it is failed during deployment.
    But if I use CASE instead of DECODE, it works fine.
    Can we use DECODE in OWB???
    Thanks
    Raj

    Hi,
    In OWB 10gR2, if your are using only one DECODE in an expression, it's working. The package will compile when deploying the mapping. OWB will replace the DECODE by a CASE.
    But when you are using nested decode in an expression ( for example : decode(col1, 1, 'M', decode(col2, 'Madame', 'Mme', null)) ) only the first one is replaced by a case at deployment.
    In ROW_BASED mode, text of the expression is used outside of an sql statement and deployment will fails with "PLS-00204: function or pseudo-column 'DECODE' may be used inside a SQL statement only."
    If operating mode for the mapping is set to SET_BASED, it's working because the expression is used in an sql statement.
    I have logged a SR in metalink for this issue and a bug is opened (bug 5414112).
    But I agree with you, it's better to use case statement.
    Bernard

  • How to use instr functions?

    Hi guys,
    I have a table like this:
    name data
    a 10101000U000
    b 011U11001100
    c 0U1001001001
    d 01U010100010
    I want to get the position of "U" in data column, like:
    name position of U
    a 9
    b 4
    c 2
    d 3
    what should I do? I use "instr" function, but failed. can anyone help me on this?
    Thanks.

    Example for you:
    [email protected]> select instr('10101000U000','U') from dual;
    INSTR('10101000U000','U')
    9
    [email protected]> select instr('011U11001100','U') from dual;
    INSTR('011U11001100','U')
    4
    Best Regards
    Krystian Zieja / mob

  • I want single update query without use the function.

    I want to update sells_table selling_code field with max date product_code from product table.
    In product table there is multiple product_code date wise.
    I have been done it with below quey with the use of function but can we do it in only one update query
    without use the function.
    UPDATE sells_table
    SET selling_code = MAXDATEPRODUCT(ctd_vpk_product_code)
    WHERE NVL(update_product_flag,0) = 0 ;
    CREATE OR REPLACE FUNCTION HVL.maxdateproduct (p_product IN VARCHAR2) RETURN NUMBER
    IS
    max_date_product VARCHAR2 (100);
    BEGIN
    BEGIN
    SELECT NVL (TRIM (product_code), 0)
    INTO max_date_product
    FROM (SELECT product_code, xref_end_dt
    FROM product
    WHERE TO_NUMBER (p_product) = pr.item_id
    ORDER BY xref_end_dt DESC)
    WHERE ROWNUM = 1; -- It will return only one row - max date product code
    EXCEPTION
    WHEN OTHERS
    THEN
    RETURN 0;
    END;
    RETURN max_date_product;
    END maxdateproduct;
    Thanks in Advance.

    Hi,
    Something like this.
    update setlls_table st
            set selling_code =(select nvl(trim(product_code)) from 
                                  (select product_code
                                          , rank() over (partition by item_id order by xref_end_dt DESC) rn
                                       from product
                                   ) pr
                                   where rn =1
                                         and pr.item_id = st.ctd_vpk_product_code
                               ) where NVL(update_product_flag,0) = 0 ;As such not tested due to lack of input sample.
    Regards
    Anurag Tibrewal.

  • Using Previous function in summary rows?

    Hi,
    I have a requirment, where I have to use the value got in previous column in the summary row.
    The scenario is as follows.
    There are Product, Quantity on Hand , Order Type and Date column. I am using cross tab, As I have to use the details of columns for each date.
    So date will be spreaded across table as there are more dates.
    In summary column, I would like to do a calcuation for each date. And I should use the calculated amount on one date in the next date and the calcuation continues.
    I am trying to use previous function, but its showing computation error.
    I am attaching a excel sheet with a sample example for easy understanding.
    The calculation which I used in summary row is avialble in formula section, when we select the column.
    Thanks in Advance.
    Regards
    Gowtham

    Hi BOCP,
    Yes, I am trying to use this function in Summary after Break.
    Sorry, I missed out attachment. And I didn't find a way to attach it.
    Suresh,
    I didn't find last() function in WebI Editor. I am using BO XI R2.
    Thanks a lot.
    Regards,
    Gowtham Sen.

  • How can I use SUM function to calculate # of employees in the comp.&deptnt?

    I've got two tables: employee & department. I am trying to calculate total employees by department and total employees by the entire company. I know I need to use SUM function, but I only can calculate total employees by department & by company separately. I need to get this output:
    DEPT_NAME     DEPT_TOTAL_SALARY         COMPANY_TOTAL_SALARY
    RESEARCH                  10875                        29025
    SALES                      9400                        29025   
    ACCOUNTING                 8750                        29025     
    This is my code:
    SELECT department_name, SUM(salary) as total_salary
    FROM employee, department
    WHERE employee.department_id = department.department_id
    GROUP BY department_name;
    SELECT SUM(salary)
    FROM employee;
    Can somebody help please?
    Thank you in advance.Edited by: user13675672 on Jan 30, 2011 2:29 PM
    Edited by: user13675672 on Jan 30, 2011 2:31 PM

    Hi, Peter
    Peter Gjelstrup wrote:
    ... There might be a smarter way, with no re-select.You're right, as usual.
    SELECT       d.dname
    ,       SUM (e.sal)               AS dept_tot_sal
    ,       SUM (SUM (e.sal)) OVER ()     AS comp_tot_sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON     d.deptno     = e.deptno
    GROUP BY  d.dname
    ;Analytic functions are computed after aggregate functions, so an aggregate function can be nested inside an analytic function.
    Another way (without a sub-query, at least) would be SELECT DISTINCT, with only analytic functions.
    SELECT DISTINCT
           d.dname
    ,       SUM (e.sal) OVER (PARTITION BY  d.dname)     AS dept_tot_sal
    ,       SUM (e.sal) OVER ()                    AS comp_tot_sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON     d.deptno     = e.deptno
    ;

  • I can access a function in a package using OCI drivers but not PDO drivers

    Hello all, i am a newbie to Oracle and its drivers for PHP. I would like to use PDO, and I have my database activity in packages, which have procedures and functions. My package has overloaded functions and that has been giving me a tough time with these drivers. So one signature of my function get_data contains a four arguments and all four are numbers, while another signature of get_data has the first two as numbers and the next two as varchar2. So when I try to access this function which is part of a package, I am able to retrieve data, and the driver I am using is OCI8, but when I try to do the same with PDO, it does not work. It gives me this error,
    *General error: 6553 OCIStmtExecute: ORA-06553: PLS-307: too many declarations of 'GET_DATA' match this call  (/var/www/php-5.3.3/ext/pdo_oci/oci_statement.c:146)' in /var/www/pdo_check.php:251 Stack trace: #0 /var/www/pdo_check.php(251): PDOStatement->execute() #1 /var/www/pdo_check.php(345): dbPDO->execPackage2() #2 {main} thrown in /var/www/pdo_check.php on line 251 *
    I got this error earlier with OCI drivers, then I added the datatype while binding the values.
    Has anybody had this headache earlier??
    ##Works
    *$qu = oci_parse($connect, 'select pack.get_data(:p1,:p2,:p3,:p4)as rc from dual');
    $p1 = (int)121;
    $p2 = (int)222;
    $p3 = (int)324;
    $p4 = (int)001;
    oci_bind_by_name($qu,":p1",$p1,10,OCI_B_INT);
    oci_bind_by_name($qu,":p2",$p2,10,OCI_B_INT);
    oci_bind_by_name($qu,":p3",$p3,10,OCI_B_INT);
    oci_bind_by_name($qu,":p4",$p4,10,OCI_B_INT);
    oci_execute($qu) or die("did not execute");
    $r = oci_fetch_array($qu);*
    ##Does not work
    *$sql = 'select pack.get_data(:p1,:p2,:p3,:p4) from dual';
    $result = $this->dbConnect->prepare($sql);
    $p1 = (int)2;
    $p2 = (int)2;
    $p3 = (int)2;
    $p4 = (int)6;
    $result->bindParam(':p1', $p1, PDO::PARAM_INT);
    $result->bindParam(':p2', $p2, PDO::PARAM_INT);
    $result->bindParam(':p3', $p3, PDO::PARAM_INT);
    $result->bindParam(':p4', $p4, PDO::PARAM_INT);
    $result->execute();*
    I am still perplexed why is PDO giving me an error, when I have virtually mentioned everything is asks for?

    I think the only person who can really answer this question is Chris Jones. For my money I tend to steer clear of PDO as it is a bit quirky ( at least in my experience ) and it does not support reference cursors.

  • Valid packages goes invalid when executing application

    Friends of pl/sql
    When we execute our application we find that 2 of our main packiages go invalid for no reason. The packages compiles just fine when we then compile them. So, no syntax errors. But it stops our application with a lovely "existing state of packages have been discarded......." type error. Not too nice.
    What are some of the things to check on for why the package goes invalid ?
    We are using TOAD and sql*monitor to trace the process at the moment...........
    Any solutions out there ?
    Environment : Oracle Enterprise Linux 5 on Oracle 11.1.0.6 (latest patch available). Oracle 11 client as well.
    Edited by: ow001294 on Apr 15, 2009 9:24 AM

    One of my older standard responses (haven't use this in a while)..
    Packages tend to fail because of their "package state". A package has a "state" when it contains package level variables/constants etc. and the package is called. Upon first calling the package, the "state" is created in memory to hold the values of those variables etc. If an object that the package depends upon e.g. a table is altered in some way e.g. dropped and recreated, then because of the database dependencies, the package takes on an INVALID status. When you next make a call to the package, Oracle looks at the status and sees that it is invalid, then determines that the package has a "state". Because something has altered that the package depended upon, the state is taken as being out of date and is discarded, thus causing the "Package state has been discarded" error message.
    If a package does not have package level variables etc. i.e. the "state" then, taking the same example above, the package takes on an INVALID status, but when you next make a call to the package, Oracle sees it as Invalid, but knows that there is no "state" attached to it, and so is able to recompile the package automatically and then carry on execution without causing any error messages. The only exception here is if the thing that the package was dependant on has changes in such a way that the package cannot compile, in which case you'll get an Invalid package type of error.
    And if you want to know how to prevent discarded package states....
    Move all constants and variables into a stand-alone package spec and reference those from your initial package. Thus when the status of your original package is invlidated for whatever reason, it has no package state and can be recompiled automatically, however the package containing the vars/const will not become invalidated as it has no dependencies, so the state that is in memory for that package will remain and can continue to be used.
    As for having package level cursors, you'll need to make these local to the procedures/functions using them as you won't be able to reference cursors across packages like that (not sure about using REF CURSORS though.... there's one for me to investigate!)
    This first example shows the package state being invalided by the addition of a new column on the table, and causing it to give a "Package state discarded" error...
    SQL> set serveroutput on
    SQL>
    SQL> create table dependonme (x number)
      2  /
    Table created.
    SQL>
    SQL> insert into dependonme values (5)
      2  /
    1 row created.
    SQL>
    SQL> create or replace package mypkg is
      2    procedure myproc;
      3  end mypkg;
      4  /
    Package created.
    SQL>
    SQL> create or replace package body mypkg is
      2    v_statevar number := 5; -- this means my package has a state
      3
      4    procedure myproc is
      5      myval number;
      6    begin
      7      select x
      8      into myval
      9      from dependonme;
    10
    11      myval := myval * v_statevar;
    12      DBMS_OUTPUT.PUT_LINE('My Result is: '||myval);
    13    end;
    14  end mypkg;
    15  /
    Package body created.
    SQL>
    SQL> exec mypkg.myproc
    My Result is: 25
    PL/SQL procedure successfully completed.
    SQL>
    SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
      2  /
    OBJECT_NAME
    OBJECT_TYPE         STATUS
    MYPKG
    PACKAGE             VALID
    MYPKG
    PACKAGE BODY        VALID
    SQL>
    SQL>
    SQL> alter table dependonme add (y number)
      2  /
    Table altered.
    SQL>
    SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
      2  /
    OBJECT_NAME
    OBJECT_TYPE         STATUS
    MYPKG
    PACKAGE             VALID
    MYPKG
    PACKAGE BODY        INVALID
    SQL>
    SQL> exec mypkg.myproc
    BEGIN mypkg.myproc; END;
    ERROR at line 1:
    ORA-04068: existing state of packages has been discarded
    ORA-04061: existing state of package body "SCOTT.MYPKG" has been invalidated
    ORA-06508: PL/SQL: could not find program unit being called: "SCOTT.MYPKG"
    ORA-06512: at line 1
    SQL>
    SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
      2  /
    OBJECT_NAME
    OBJECT_TYPE         STATUS
    MYPKG
    PACKAGE             VALID
    MYPKG
    PACKAGE BODY        INVALID
    SQL>
    SQL> exec mypkg.myproc
    PL/SQL procedure successfully completed.
    SQL>
    SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
      2  /
    OBJECT_NAME
    OBJECT_TYPE         STATUS
    MYPKG
    PACKAGE             VALID
    MYPKG
    PACKAGE BODY        VALIDAnd this next example shows how having the package variables in their own package spec, allows the package to automatically recompile when it is called even though it became invalidated by the action of adding a column to the table.
    SQL> drop table dependonme
      2  /
    Table dropped.
    SQL>
    SQL> drop package mypkg
      2  /
    Package dropped.
    SQL>
    SQL> set serveroutput on
    SQL>
    SQL> create table dependonme (x number)
      2  /
    Table created.
    SQL>
    SQL> insert into dependonme values (5)
      2  /
    1 row created.
    SQL>
    SQL> create or replace package mypkg is
      2    procedure myproc;
      3  end mypkg;
      4  /
    Package created.
    SQL>
    SQL> create or replace package mypkg_state is
      2    v_statevar number := 5; -- package state in seperate package spec
      3  end mypkg_state;
      4  /
    Package created.
    SQL>
    SQL> create or replace package body mypkg is
      2    -- this package has no state area
      3
      4    procedure myproc is
      5      myval number;
      6    begin
      7      select x
      8      into myval
      9      from dependonme;
    10
    11      myval := myval * mypkg_state.v_statevar;  -- note: references the mypkg_state package
    12      DBMS_OUTPUT.PUT_LINE('My Result is: '||myval);
    13    end;
    14  end mypkg;
    15  /
    Package body created.
    SQL>
    SQL> exec mypkg.myproc
    My Result is: 25
    PL/SQL procedure successfully completed.
    SQL>
    SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
      2  /
    OBJECT_NAME
    OBJECT_TYPE         STATUS
    MYPKG
    PACKAGE             VALID
    MYPKG
    PACKAGE BODY        VALID
    SQL>
    SQL> alter table dependonme add (y number)
      2  /
    Table altered.
    SQL>
    SQL> select object_name, object_type, status from user_objects where object_name = 'MYPKG'
      2  /
    OBJECT_NAME
    OBJECT_TYPE         STATUS
    MYPKG
    PACKAGE             VALID
    MYPKG
    PACKAGE BODY        INVALID
    SQL>
    SQL> exec mypkg.myproc
    My Result is: 25
    PL/SQL procedure successfully completed.

Maybe you are looking for