MIN in select SINGLE  query.

I need to find a single record with lowest DDUP.
If there are 2 records exist, then i need a single record with lowest DDUP.
loop at it_mara.
  SELECT SINGLE EKORG MATNR MFRPN ZEINR KUNNRS MIN( DDUP ) DCURR
                  FROM ZNVT_PRICE
                  INTO CORRESPONDING FIELDS OF LW_ZNVT_PRICE
                  WHERE EKORG  EQ P_EKORG       AND
                        MATNR  EQ IT_MARA-MATNR AND
                        MFRPN  EQ IT_MARA-MFRPN AND
                        ZEINR  EQ IT_MARA-ZEINR AND
                        KUNNRS EQ IT_MARA-KUNNR AND
                        DATAB  LE SY-DATLO      AND
                        DATBI  GE SY-DATLO
                  GROUP BY EKORG MATNR MFRPN ZEINR KUNNRS DCURR.
endloop.
there is only one record in the table ZNVT_PRICE. (1234.00)
Some times i am getting 1234.
Some times 0.00.
I need to find a single record with lowest DDUP.
If there are 2 records exist, then i need a single record with lowest DDUP.
if I do not use GROUP BY i am getting error.
I have to use SELECT SINGLE.
Guys...please help me to write reliable query.

Hi,
Instead of SELECT SINGLE use
SELECT.. UP TO 1 ROWS
ENDSELECT.
It will also be very fast and suit your requirement.
Regards,
Atish

Similar Messages

  • Select single query working unexpectedly

    Hi all,
    I have used below select single * query as shown :
    I have data in my table S022 as shown below, it has 2 records for material and aufnr combination :
    WERKS  ARBPL    kapar    MATNR                AUFNR      
    w1        ar1        004          mat1             000300156789
    w1        ar2                        mat1             000300156789
    The code used :
    select single *               
       from s022                   
      where werks = itab-ltap-werks  "w1
        and matnr = w_matnr         "mat1
        and aufnr = w_aufnr. " 000300156789
    runtime select query is picking second record i.e of ar2.
    I hope it should have picked ar1 record but its doesnt .
    Also sometimes it picks 1st record for different data and for this data it picks the second record.
    Kindly help me to explain why its not picking the first record.
    Regards.

    ujjwal_d15 wrote:
    It is as per the data in the table . The records are one below the another in database table.
    > So i feel it should have picked the first record.
    Hello Ujjwal,
    The records shown in the databrowser is a snapshot of the entries in the DB & not how the recs are actually stored!
    In RDBMS the sequence of entries is not defined at the DB layer. In SELECT SINGLE the 1st rec to be hit is returned to the result set. In your case this is the 2nd rec.
    BR,
    Suhas

  • Problem in SELECT SINGLE Query

    Hi,
    I am writing a small quesry in PS, Though the entry exist in database table PRPS, The sy-subrc is 4 for this query.Can u help me.
    data : wa_src_prps like prps-posid.
    start-of-selection.
    wa_src_prps  = '3-3310-02-01-01-10-20'.
        DATA: lv_pbukr LIKE prps-pbukr.
        CLEAR: lv_pbukr.
        SELECT SINGLE pbukr INTO lv_pbukr
                             FROM prps
                             WHERE posid EQ wa_src_prps.
    if sy-subrc = 0.
    write:/5 wa_src_prps, lv_pbukr.
    endif.

    hi,
    DATA : wa_src_prps LIKE prps-posid.
    START-OF-SELECTION.
      wa_src_prps = '0-1000-0'.
    " Conversion Routine for domain PS_POSID
      CALL FUNCTION 'CONVERSION_EXIT_ABPSN_INPUT'
        EXPORTING
          input  = wa_src_prps
        IMPORTING
          output = wa_src_prps.
      DATA: lv_pbukr LIKE prps-pbukr.
      CLEAR: lv_pbukr.
      SELECT SINGLE pbukr INTO lv_pbukr
      FROM prps
      WHERE posid EQ wa_src_prps.
      IF sy-subrc = 0.
        WRITE:/5 wa_src_prps, lv_pbukr.
      ENDIF.

  • All selected 'n' consecutive rows in retrieved in a single query

    hello,
    I have table T with 50,000 rows
    create table T
    (student_id number,
    class_id number,
    quiz_id number,
    marks number)
    some sample rows like
    INSERT INTO T VALUES (1,1, 1, 50);
    INSERT INTO T VALUES (2,2, 2, 40);
    INSERT INTO T VALUES (3,1, 3, 34);
    INSERT INTO T VALUES (1,1, 4, 10);
    INSERT INTO T VALUES (1,1, 5, 30);
    INSERT INTO T VALUES (1,1, 6, ‘29);
    INSERT INTO T VALUES (3,2, 7, 34);
    INSERT INTO T VALUES (3,2, 8, 33);
    INSERT INTO T VALUES (3,2, 9, 56);
    INSERT INTO T VALUES (1,1, 7, 90);
    INSERT INTO T VALUES (2,2, 8, 0,);
    INSERT INTO T VALUES (1,1, 8, 80);
    INSERT INTO T VALUES (2,2, 8, 65);
    INSERT INTO T VALUES (1,1, 9, ‘34);
    INSERT INTO T VALUES (2,2, 9, 11);each student belongs to one class_id. each student participates in many quizes. each quiz has its unique id. each student can appear once in a quiz_id
    I am doing the below analysis and query:
    1. with below query I am finding which student_id had most marks in any 3 successive quizes (see the 3-1 part below) in the query..
    SELECT QUIZ_ID,
          STUDENT_ID,
    SUM (MARKS) OVER (PARTITION BY STUDENT_ID ORDER BY QUIZ_ID1
    RANGE BETWEEN CURRENT ROW AND (3-1) FOLLOWING) consecMARKS , MARKS   FROM
          (SELECT QUIZ_ID,
            STUDENT_ID,
            MARKS,
          ROW_NUMBER() OVER (PARTITION BY STUDENT_ID ORDER BY T.QUIZ_ID) QUIZ_ID1
          FROM T
          WHERE MARKS IS NOT NULL
          ORDER BY 1
        ORDER BY 3 DESC
    SQL> /
       QUIZ_ID STUDENT_ID CONSECMARKS
             7          1         170
             6          1         166
             8          1         129
             5          1         106
             8          3          89
             8          2          76
             3          3          68
             7          3          67
             8          2          65
             1          1          60
             9          3          56
       QUIZ_ID STUDENT_ID CONSECMARKS
             9          1          49
             2          2          40
             4          1          40
             9          2          11
    15 rows selected.With above query, I can play around and find for any 'n' number of consecutive quizes, like marks in 2 consecutives quizes, 3, 4 and so on but for each 'n' value I've to run a seperate query mentioning (2-1) or (3-1) or (4-1) and so on..
    since my table is big and there are about 400 quizes so what I want to find out is for each 'n' consecutive quiz (from 1 to 400) which student had most marks for each consecutie 'n' quiz. Like in 1 (consecutive) quiz which student had the highest marks and then 2 conseuctive quiz who had most marks and then in 3 consecutive quiz who had most marks and so on till 400 consecutive quiz who had most marks... rather than running query for each 'n' value seperately i want a single query that can give me a summary of most marks in each n consecutive quizes...
    my sample output is:
    Nth consecutive quiz     student_id    sum(marks)
    1                        1              90
    2                        1              170
    3                        1              246
    4
    100
    200
    300
    400                      ?              ?   Is this possible to get the above output from one single query? If there are two or more students with equal most marks for any 'n' conseutive quizes then both should come in the summary.
    Hope I have been able to put up my question clearly.
    regards
    Ramis

    Something like:
    SELECT  N,
            QUIZ_ID,
            STUDENT_ID,
            SUM(MARKS) OVER (PARTITION BY N,STUDENT_ID ORDER BY QUIZ_ID1 RANGE BETWEEN CURRENT ROW AND (N-1) FOLLOWING) consecMARKS,
            MARKS
      FROM  (SELECT  QUIZ_ID,
                     STUDENT_ID,
                     MARKS,
                     ROW_NUMBER() OVER (PARTITION BY STUDENT_ID ORDER BY T.QUIZ_ID) QUIZ_ID1
               FROM  T
               WHERE MARKS IS NOT NULL
             SELECT  LEVEL N
               FROM  DUAL
               CONNECT BY LEVEL <= (
                                    SELECT  COUNT(DISTINCT QUIZ_ID)
                                      FROM  T
        ORDER BY N,
                 consecMARKS DESC
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             1          7          1          90         90
             1          8          1          80         80
             1          8          2          65         65
             1          9          3          56         56
             1          1          1          50         50
             1          2          2          40         40
             1          9          1          34         34
             1          7          3          34         34
             1          3          3          34         34
             1          8          3          33         33
             1          5          1          30         30
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             1          6          1          29         29
             1          9          2          11         11
             1          4          1          10         10
             1          8          2           0          0
             2          7          1         170         90
             2          6          1         119         29
             2          8          1         114         80
             2          8          3          89         33
             2          8          2          76         65
             2          3          3          68         34
             2          7          3          67         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             2          8          2          65          0
             2          1          1          60         50
             2          5          1          59         30
             2          9          3          56         56
             2          2          2          40         40
             2          4          1          40         10
             2          9          1          34         34
             2          9          2          11         11
             3          7          1         204         90
             3          6          1         199         29
             3          5          1         149         30
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             3          7          3         123         34
             3          8          1         114         80
             3          2          2         105         40
             3          3          3         101         34
             3          1          1          90         50
             3          8          3          89         33
             3          8          2          76         65
             3          8          2          76          0
             3          4          1          69         10
             3          9          3          56         56
             3          9          1          34         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             3          9          2          11         11
             4          6          1         233         29
             4          5          1         229         30
             4          7          1         204         90
             4          4          1         159         10
             4          3          3         157         34
             4          7          3         123         34
             4          1          1         119         50
             4          2          2         116         40
             4          8          1         114         80
             4          8          3          89         33
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             4          8          2          76          0
             4          8          2          76         65
             4          9          3          56         56
             4          9          1          34         34
             4          9          2          11         11
             5          5          1         263         30
             5          4          1         239         10
             5          6          1         233         29
             5          1          1         209         50
             5          7          1         204         90
             5          3          3         157         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             5          7          3         123         34
             5          2          2         116         40
             5          8          1         114         80
             5          8          3          89         33
             5          8          2          76          0
             5          8          2          76         65
             5          9          3          56         56
             5          9          1          34         34
             5          9          2          11         11
             6          1          1         289         50
             6          4          1         273         10
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             6          5          1         263         30
             6          6          1         233         29
             6          7          1         204         90
             6          3          3         157         34
             6          7          3         123         34
             6          2          2         116         40
             6          8          1         114         80
             6          8          3          89         33
             6          8          2          76          0
             6          8          2          76         65
             6          9          3          56         56
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             6          9          1          34         34
             6          9          2          11         11
             7          1          1         323         50
             7          4          1         273         10
             7          5          1         263         30
             7          6          1         233         29
             7          7          1         204         90
             7          3          3         157         34
             7          7          3         123         34
             7          2          2         116         40
             7          8          1         114         80
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             7          8          3          89         33
             7          8          2          76          0
             7          8          2          76         65
             7          9          3          56         56
             7          9          1          34         34
             7          9          2          11         11
             8          1          1         323         50
             8          4          1         273         10
             8          5          1         263         30
             8          6          1         233         29
             8          7          1         204         90
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             8          3          3         157         34
             8          7          3         123         34
             8          2          2         116         40
             8          8          1         114         80
             8          8          3          89         33
             8          8          2          76          0
             8          8          2          76         65
             8          9          3          56         56
             8          9          1          34         34
             8          9          2          11         11
             9          1          1         323         50
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             9          4          1         273         10
             9          5          1         263         30
             9          6          1         233         29
             9          7          1         204         90
             9          3          3         157         34
             9          7          3         123         34
             9          2          2         116         40
             9          8          1         114         80
             9          8          3          89         33
             9          8          2          76          0
             9          8          2          76         65
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             9          9          3          56         56
             9          9          1          34         34
             9          9          2          11         11
    135 rows selected.
    SQL> SY.

  • Selecting data from single table with different condition in single query

    Hi everybody...
    I have one table with col1, col2, col3, col4, col5... as columns.
    I want to select col1, col2, col3 with condition (x=y and a=b and c=d)
    I want to select col4, col5 with condition (x=y and a=b and m=n )
    in single query...
    Thanx for ur help

    Given this data set...
    SQL> select * from oddity
      2  /
          COL1       COL2       COL3       COL4       COL5 A X C M
             1          2          3          4          5 B Y   M
             1          2          3          4          5 A Y C N
             1          2          3          4          5 A Y D M
             1          2          3          4          5 A Y D N
             1          2          3          4          5 B Y D N
             1          2          3          4          5 B Y D U
    6 rows selected.
    SQL>The following query meets the requirements. Of course, the requirements as stated are incomplete. I ahave assumed that we select all five columns if C=D andM=N.
    SQL> SELECT decode(c, 'D', col1, '0') AS col1
      2         , decode(c, 'D', col2, '0') AS col2
      3         , decode(c, 'D', col3, '0') AS col3
      4          , decode(m, 'N', col4, '-8') AS col4
      5           , decode(m, 'N', col5, '-8') AS col5
      6  FROM oddity
      7  WHERE a = 'B'
      8  AND  x = 'Y'
      9  /
          COL1       COL2       COL3       COL4       COL5
             0          0          0         -8         -8
             1          2          3          4          5
             1          2          3         -8         -8
    SQL> Cheers, APC

  • Different selection in a single query according to an ID

    Hi
    I'm looking for a way to perform different selections in a single query according to a specific value:
    Here is the first selection:
      select g.*,gf.*,gs.*         
      FROM graphs g
      LEFT JOIN graph_frames gf on g.graph_id = gf.graph_id
      LEFT JOIN graph_sets gs on gf.frame_id = gs.frame_id
      WHERE g.graph_id = :IDHere is the second selection:
      SELECT gg.graph_id, gg.graph_name
      FROM generic_graphs gg
      INNER JOIN generic_graph_frames ggf on gg.graph_id = ggf.graph_id
      INNER JOIN generic_graph_sets ggs on ggf.frame_id = ggs.frame_id
      WHERE gg.graph_id = :IDNow, the ID cannot be in both the tables and I want to perform that in a single query, UNION cannot be applied since the tables are different.
    Any ideas?
    Edited by: BluShadow on 14-Sep-2011 09:09
    added {noformat}{noformat} tags.  Please read {message:id=9360002} and learn to do this yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Example of consolidating the columns...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select &id as id from dual)
      2  select e.empno, e.ename, e.job, e.mgr, d.deptno, d.dname, d.loc
      3  from   (select * from emp cross join t where empno = t.id) e
      4         full outer join
      5         (select * from dept cross join t where deptno = t.id) d
      6*        on (1=1)
    SQL> /
    Enter value for id: 7521
    old   1: with t as (select &id as id from dual)
    new   1: with t as (select 7521 as id from dual)
         EMPNO ENAME      JOB              MGR     DEPTNO DNAME          LOC
          7521 WARD       SALESMAN        7698
    SQL> /
    Enter value for id: 10
    old   1: with t as (select &id as id from dual)
    new   1: with t as (select 10 as id from dual)
         EMPNO ENAME      JOB              MGR     DEPTNO DNAME          LOC
                                                       10 ACCOUNTING     NEW YORK
    SQL>Though, this would be considered poor design because you are trying to query two disperate things, so they should be treated differently. i.e. in my example, I should already know if I'm querying an employee or a department beforehand.

  • Select top row in Single Query?

    Hi
    Can somebody help me to write a query to get the first row after order by clause using single query alone.
    Example:
    I can write following query to select first row
    select * from (selec * from t order by col1) where rownum = 1;
    But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
    Please help me.

    Raghav.786 wrote:
    Hi
    Can somebody help me to write a query to get the first row after order by clause using single query alone.
    Example:
    I can write following query to select first row
    select * from (selec * from t order by col1) where rownum = 1;
    But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
    Please help me.
    What Oracle version are you?
    If you have 12c you can use
    select col1,...
      from t
    order by col1
    fetch first 1 row only;
    If less than 12c, you have can't do it without a subquery.
    What are you actually trying to do? Read Re: 2. How do I ask a question on the forums?
    and follow the advice there by giving example create table and insert sample data statements and
    explaining clearly what you are trying to do. Then we can help more.

  • Single Query for getting total no of records N getting records from a selected range

    Hi,
    Got the below query:
    SELECT a.*, rowid FROM (SELECT name, postcode FROM Tbl ORDER BY name asc)a WHERE ROWNUM <=30
    MINUS
    SELECT b.*, rowid FROM (SELECT name, postcode FROM Tbl ORDER BY name asc) b WHERE ROWNUM <= 10
    Though I got the results right, I also want to know the total no of records from "SELECT name, postcode FROM Tbl ORDER BY name asc". Does anyone knows how to do it in a single query?
    Thanks.

    hi Carol
    The following output may help you.
    SQL> l
    1 select * from emp where (rowid,0) in (select rowid,mod(rownum,10)-rownum from emp)
    2 minus
    3* select * from emp where (rowid,0) in (select rowid,mod(rownum,6)-rownum from emp)
    SQL> /
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7839 KING PRESIDENT 17-NOV-81 5000 10
    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
    7876 ADAMS CLERK 7788 12-JAN-83 1100 20
    7900 JAMES CLERK 7698 03-DEC-81 950 30
    The above query fetches the 6,7,8,9th records only.
    Well my suggestion would be not to use ROWNUM directly in where clause since it changes dynamically. it is not a fixed value. for example pls see the result.
    SQL> select rownum,empno,ename,sal,job from emp where sal > 3000;
    ROWNUM EMPNO ENAME SAL JOB
    1 7839 KING 5000 PRESIDENT
    SQL> select rownum,empno,ename,sal,job from emp where sal > 1000;
    ROWNUM EMPNO ENAME SAL JOB
    1 7566 JONES 2975 MANAGER
    2 7654 MARTIN 1250 SALESMAN
    3 7698 BLAKE 2850 MANAGER
    4 7782 CLARK 2450 MANAGER
    5 7788 SCOTT 3000 ANALYST
    6 7839 KING 5000 PRESIDENT
    7 7844 TURNER 1500 SALESMAN
    8 7876 ADAMS 1100 CLERK
    9 7902 FORD 3000 ANALYST
    10 7934 MILLER 1300 CLERK
    10 rows selected.
    SQL> select * from emp where rownum = 1;
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7566 JONES MANAGER 7839 02-APR-81 2975 20
    The record of employee KING is getting the rownum differently.
    My understanding (out of my little knowledge) is the rownum values are assigned to the records only after the records are read physically and after applying the conditions(without rownum). Then the row numbers (rownum) is assigned to the records. Hence the rownum is not constant to a record since it is a dynamic value.
    Well i would like to know the suggestions of the ORACLE EXPERTS here in the discussion forum.
    If my finding is correct then OK if not Pls excuse me and pls give the correct solution
    Regards
    Prakash Eranki
    [email protected]

  • Update or select in a single query

    Hi , I want to select or update from a single query. Can I do that ?
    I tried Merge into, but it is for Update or Insert.
    Can anyone help me please. I do not want to use stored Proc/function.

    userPrasad wrote:
    I want to fire a update or merge statement inside a select SQL. Is there any way to do that ?Just to clarify:
    It is possible to UPDATE based on a SELECT condition within SQL, i.e.,
    UPDATE table1 t1
       SET col1 = new_val
    WHERE col2 IN (
        SELECT col2
           FROM table2 t2
          WHERE t1.col1 = t2.col1
              AND col1 = old_val);or to MERGE:
    MERGE into table1 t1
    USING (SELECT * FROM table2) t2
      ON (t1.col1 = t2.col1)
    WHEN MATCHED...
    WHEN NOT MATCHED...Both of those will use a SELECT, and MERGE can UPDATE, INSERT, both or either one, or none.
    Is that what you had in mind?

  • Performance issues with respect scheme registration,select & insert query

    I am facing performance issues with respect to schema registration,Select & insert query towards 10.2.0.3 version.It is taking around 45 minutes to register schema and it is taking around 5 min to insert a single document into xml db where as it was taking less than min to insert a single document into xml db of 9.2.0.6 version.Would like to know the issue and solution to resolve this issue.Please help me out on this as it is very urgent for me

    Since it appears that this is an XML DB specific question, you're probably better off posting in the XML DB. The folks over there have much more experience with the ins and outs of that particular product.
    Justin

  • Double aggregation in a single query block doesn't make any sence.

    How can I argue with something that apparently has been cast in stone by ANSI SQL committee? Well the answer is famous: "Search any park in any city: you'll find no statue of committee".
    OK, why
    select count(1) from (
    select deptno from emp
    group by deptno
    is an easy to understand query, and why
    select count(count(*)) from emp
    group by deptno
    is not? I already mentioned one reason why count shouldn't accept any arguments, therefore count(count(*)) is a nonsence.
    The other reason is that aggregation without grouping is essentially aggregation within a single group. Once you realize that
    select sum(1) from emp
    is the same as
    select sum(1) from emp
    group by -1
    (where -1 or any other constant for that matter is a dummy pseudocolumn), then it becomes obvious that what we are doing in the infamous
    select count(count(*)) from emp
    group by deptno
    is a query with two blocks
    select count(1) from (
    select deptno from emp
    group by deptno
    ) group by -1
    We are not allowed to combine two "group by" into a single query, aren't we?

    Aggregate function always goes together with grouping. Grouping can partition the set of rows into many classes or a single class. Therefore, if we have 2 nested aggregation functions, we'd better be able to identify the corresponding groupings easily:
    select state, avg(min(tax_return)) from household
    group by city, state then statewhich is a shorthand for
    select state, avg(m) from (
       select city, state, min(tax_return) m
       from household
       group by city, state
    ) group by stateSpeaking of double aggregation, it is frequent in graph queries. The part explosion query is posted repeatedly virtually every month on this fine forum:-) The part explosion is double aggregation: multiply the quantities along each path in the assembly hierarchy. Then add the quantities along alternative paths. Likewise, finding a shortest path between two nodes in a graph is double aggregation query. First, we calculate the length buy adding the distances along each path, and then we choose a path with minimal length. Wouldn't it be nice to have this double aggregation wired into the connect by syntax? Note that connect_by_path is a surrogate aggregate which concatenates strings. People invent all kind of functions which parse this path and make other aggregates out of this value (such as sum and product).

  • How to use multiple aggregate functions in single query

    hi to all
    The output will be giving first_name,last_name,max(salary),min(salary) and the output will be department wise.From employees table in single query
    output will be:
    first_name|last_name|max(salary)|min(salary)

    SELECT first_name||' '||last_name as ename,
           MIN(sal) KEEP (DENSE_RANK FIRST ORDER BY sal) OVER (PARTITION BY deptno) "Lowest",
           MAX(sal) KEEP (DENSE_RANK LAST ORDER BY sal) OVER (PARTITION BY deptno) "Highest"
    FROM   emp
    ORDER BY deptno, sal;Edited by: Ramio on Jan 10, 2012 10:43 PM

  • How to calculate multiple aggregation in a single query

    how to find firstname ,lastname for max and min salary from employees table group by department in a single query?
    Edited by: Gnanasekar on Jan 10, 2012 6:36 AM

    check this query
    select ENAME,SAL
    from EMP
    where SAL in(select max(SAL)
                       from EMP
                      group by DEPTNO)
    or SAL in(select min(SAL)
                 from EMP
                  group by DEPTNO)Hope this will help you..
    You should ask this question at sql/plsql forum
    If someone's response is helpful or correct, please mark it accordingly.

  • Combine 2 Queries (from SAME table) into a SINGLE query

    I have this two queries (from SAME table), and want to combine into one SINGLE query, how?
    How can we use CASE WHEN THEN for such situation? 
    Query1:
    SELECT t_inner.*,
    Floor(t_inner.ProductiveTime/ 3600) || 'hr:' || LPAD(Floor(Mod(t_inner.ProductiveTime,3600) / 60),2,0) || 'min:' AS Productive_Time,
    Floor(t_inner.OperatorDownTime/ 3600) || 'hr:' || LPAD(Floor(Mod(t_inner.OperatorDownTime,3600) / 60),2,0) || 'min:' AS OperatorDown_Time
    FROM
    (SELECT SYSTEMTYPE,
    sum(TIME_TEST + TIME_STEP) AS ProductiveTime,
    sum(TIME_IDLE) AS OperatorDownTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO != '9999999999'
    GROUP BY SYSTEMTYPE ) t_inner
    Query 2:
    SELECT t_inner.*,
    Floor(t_inner.MachineDownTime/ 3600) || 'hr ' || LPAD(Floor(Mod(t_inner.MachineDownTime,3600) / 60),2,0) || 'min' AS MachineDown_Time
    FROM
    (SELECT SYSTEMTYPE,
    sum(TIME_IDLE) AS MachineDownTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO = '9999999999'
    GROUP BY SYSTEMTYPE) t_inner
    see http://postimg.org/image/koq87iyyz/  and
    http://postimg.org/image/fv3zxa38n

    with the first query, 
    SELECT t_inner.*,
    Floor(t_inner.ProductiveTime/ 3600) || 'hr:' || LPAD(Floor(Mod(t_inner.ProductiveTime,3600) / 60),2,0) || 'min' AS Productive_Time
    FROM
    (SELECT SYSTEMTYPE,
    --sum(TIME_TEST) AS TIME_TEST,
    --sum(TIME_SYSTEM) AS TIME_SYSTEM,
    --sum(TIME_STEP) AS TIME_STEP,
    --sum(TIME_IDLE) AS TIME_IDLE,
    sum(TIME_TEST + TIME_STEP) AS ProductiveTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO != '9999999999'
    GROUP BY SYSTEMTYPE) t_inner
    it gives output as from 
    http://postimg.org/image/koq87iyyz/
    with the second query,
    SELECT t_inner.*,
    Floor(t_inner.MachineDownTime/ 3600) || 'hr ' || LPAD(Floor(Mod(t_inner.MachineDownTime,3600) / 60),2,0) || 'min' AS MachineDown_Time
    FROM
    (SELECT SYSTEMTYPE,
    sum(TIME_IDLE) AS MachineDownTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO = '9999999999'
    GROUP BY SYSTEMTYPE) t_inner
    it gives output as from 
    http://postimg.org/image/fv3zxa38n/
    I want to come those 2 queries into a single query, such that it gives both outputs as above. Let me know if you need any other information. thanks.

  • How to get resultset from procedure having dynamic select sql query ?

    Hi,
    I have created a procedure, in which there is dynamic select query. The procedure has one out put parameter which gives error code. When I compile that procedure it compiles successufully. When I run it it executes successfully and gives output error code. But I don't know how to get resultset of that dynamic select sql query. I need that.
    This is the procedure:
    create or replace
    PROCEDURE uspGetProductDetailsMultiOrder
      v_DefinitionDBName IN VARCHAR2,
         v_CommonDBName IN VARCHAR2,
         v_Filter_FilledStatus IN VARCHAR2,
         v_Filter_Internal_Counterparty IN nvarchar2,
         v_Filter_NoteType IN nvarchar2,
         v_Filter_Exchange IN nvarchar2,
         v_Filter_Issuer IN nvarchar2,
         v_Filter_Product_Category  IN VARCHAR2,
         v_DateToFilter IN VARCHAR2,     
         v_Filter_FromDate IN VARCHAR2,
         v_Filter_ToDate IN VARCHAR2,
         v_Active_YN_Flag IN NVARCHAR2,
         v_Entity_ID IN NVARCHAR2,
         v_ErrorNumber  OUT NUMBER
       as
       v_SelectSQL  nvarchar2(32767);
          v_Setting_Name  nvarchar2(32767);
       v_Default_Value  nvarchar2(32767);
       v_Config_Value  nvarchar2(32767);
       v_CCY_ID  NUMBER(10,0);
       v_CCY_Data  nvarchar2(32767);
       v_CCY_List  nvarchar2(32767);
       v_Seq_Id  NUMBER(10,0);
       SWV_Active_YN_Flag NVARCHAR2(1);
       SWV_VarStr long;--varchar2(4000);
       SWV_TRANCOUNT NUMBER(10,0);
        SWV_fnc_SplitString_Id_var1 NUMBER(10,0);
       SWV_fnc_SplitString_Id_var0 NUMBER(10,0);
      CURSOR RestrictTermsheetVisibilityByC 
       IS select CS.Setting_Name,Default_Value,Config_Value
       from Config_Settings CS   LEFT OUTER JOIN Entity_Config EC  ON EC.Setting_ID = CS.Setting_ID
       where EC.Entity_ID = v_Entity_ID AND Setting_Level = 'ENTITY';
       CURSOR Get_RestrictCCY_List_Cursor IS SELECT Id_1,Data_1 FROM table(fnc_SplitString(v_Config_Value,','));
       --CURSOR Get_RestrictCCY_List_Cursor IS SELECT Id,Data FROM imp;
       CURSOR GetRestrictTemplateListCursor 
      -- is select id,data from imp;
       IS SELECT Id_1,Data_1 FROM table(fnc_SplitString(v_Config_Value,',')) ;
         --Parikshit 18-Jul-2010, active YN flag param added in SP
    BEGIN
    SWV_Active_YN_Flag := v_Active_YN_Flag;
       if SWV_Active_YN_Flag = ' '  then
          SWV_Active_YN_Flag := 'Y';
       end if;
       v_SelectSQL := ' ';
       v_SelectSQL := v_SelectSQL || ' Select ';
       v_SelectSQL := v_SelectSQL || '  NM.Note_Master_Id, NM.Product_Name, NM.Template_ID, NM.Template_Sr_No, NM.Asset, NM.Exchange, NM.Type, NM.Currency';
         --SET @SelectSQL = @SelectSQL + ' , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.Type like '' ELN%'' or NM.Type like ''RELN%'') THEN  NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.Type like '' ELN%'' or NM.Type like ''RELN%'') THEN  NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield,  NOP.Dealer_Cost_PA as Internal_Cost '
       v_SelectSQL := v_SelectSQL || ' , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.PriceList_YN = ''Y'') THEN  NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.PriceList_YN = ''Y'') THEN  NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield,  NOP.Dealer_Cost_PA as Internal_Cost ';
       v_SelectSQL := v_SelectSQL || ' , NM.Minimum_Issue_Size, NM.Maximum_Issue_Size, NM.Minimum_Tolerence_Amount, NM.Maximum_Tolerence_Amount, NM.Trigger_Amount_Warning, nvl(NM.PerUnit_Equivalent_Amount,1) as PerUnit_Equivalent_Amount,  NM.Active_YN_Flag, NM.Verify_YN_Flag ';
       v_SelectSQL := v_SelectSQL || ' , NM.Tranche_YN_Flag, NM.Launch_Date, NM.Open_Date, NM.Close_Date, NM.PreHedged_YN, NM.Created_By, NM.Created_At,  NM.Verified_At, NM.Verified_By, NM.ISIN, NM.Issuer';
       v_SelectSQL := v_SelectSQL || ' , NM.Product_Catagory as Product_Category, NM.Note_Issuer_Type as Issuer_Category, NM.Series_No as Series_No, NM.Minimum_Investment_Amount ';
         --Added by Parikshit on 14-Jun-2011, to remove the unwinding amounts from the total issue size
         --SET @SelectSQL = @SelectSQL + ' , NOP.LastTimeWhenProductModified,NOP.Nominal_Amount as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty  '
       v_SelectSQL := v_SelectSQL || ' , NOP.LastTimeWhenProductModified,(NOP.Nominal_Amount - nvl(ND.Unwind_Amount,0) ) as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty  ';
         --********************************************************END
       v_SelectSQL := v_SelectSQL || ' ,T2.Confirmed_Amount, T2.Confirmed_Shares';
       v_SelectSQL := v_SelectSQL || ' , T3.Live_Deals';
       v_SelectSQL := v_SelectSQL || ' , BS.Net_Trade_Hedged, BS.Net_Trade_Outstanding, BS.Hedged_Nominal_BUY, BS.Hedged_Nominal_SELL, BS.Outstanding_Nominal_BUY, BS.Outstanding_Nominal_SELL   ';
       v_SelectSQL := v_SelectSQL || ' , ( case    When UPPER(NM.PreHedged_YN) = ''Y'' Then ''Launched'' ';
       v_SelectSQL := v_SelectSQL || '              When ((NM.Maturity_Date IS  NOT NULL) AND to_date(NM.Maturity_Date) <= to_date(sysdate)) Then ''Matured''';
       v_SelectSQL := v_SelectSQL || '              When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NOT NULL)  Then ''Launched''';     
         --Ready to launch
       v_SelectSQL := v_SelectSQL || '              When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date  IS  NULL AND (T2.Confirmed_Amount >= NM.Minimum_Issue_Size) AND  to_date(Close_Date) > to_date(sysdate) ) Then ''Ready To Launch''';     
         --Ready to launch
       v_SelectSQL := v_SelectSQL || '              When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date  IS  NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND  to_date(Close_Date)= to_date(sysdate)    )  Then ''Ready To Launch''';     
       v_SelectSQL := v_SelectSQL || '              When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date  IS  NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND  to_date(Close_Date)< to_date(sysdate)    )  Then ''Ready To Launch''';     
         --Warning trigger reached
       v_SelectSQL := v_SelectSQL || '              When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS  NOT NULL AND (T2.Confirmed_Amount >= NM.Trigger_Amount_Warning ))  Then ''Warning Trigger Reached''';          
       v_SelectSQL := v_SelectSQL || '              Else ''Not Ready'' ';
       v_SelectSQL := v_SelectSQL || '              End)Launch_Status';
       v_SelectSQL := v_SelectSQL || ' , NI.Issuer_Code';
          v_SelectSQL := v_SelectSQL || ' , (nvl(NOP.Nominal_Amount,0) - nvl(T2.Confirmed_Amount,0)) as Unconfirmed_Amount, NM.Upfront as Upfront,   case when UPPER(NM.PreHedged_YN) = ''Y'' THEN 0 else (nvl(T2.Confirmed_Amount,0) - nvl(BS.Net_Trade_Hedged,0)) end as ReadyToHedge';
          v_SelectSQL := v_SelectSQL || ' , NOP.Hard_Margin  as Margin_Amount, NM.YearBasis as YearBasis, NM.Note_Product_Rating as Equity_Risk_Score, AD.Equity_Asset_Class ';
          v_SelectSQL := v_SelectSQL || '  , NM.Note_Product_Rating as Product_Rating,  NOP.PO_ID, AD.LotSize as Lot_Size, NM.Max_Orders_Per_Product as MAX_Orders, NOP.Order_Count as Current_Order_Count,  nvl(NM.Denomination_Ccy,NM.Currency) as Denomination_Ccy, NM.Note_Scheme_Type as Underlying_Type, NM.Note_Asset_Class as Asset_Class, NULL as Product_Created_YN, NULL as Product_Created_ID,  ( (case when NM.Note_Order_Type = '''' then N''Market'' else NM.Note_Order_Type end )  ) as  Order_Type, NOP.Spot_Price, NM.Note_Price_Link, NOP.Strike_Price, NVL(NM.C_Fixing_Frequency,''Atmaturity'') as Fixing_Frequency, NM.Document_Uploaded_YN, NM.Document_Uploaded_At, NM.Document_Uploaded_By, NM.Document_File_Name, NM.Document_File_Extension, NM.Document_File_Path, NM.CutOff_Time, NM.Soft_Tenor, NM.NM_Sn_Code_All, NULL as Note_Price_Source, AD.LongName, NVL(NM.Pricelist_YN,''N'') as Pricelist_YN, AD.AlternateIdentifierAlias as Underlying, NM.Note_Issuer_Date_Offset, NM.Counterparty as Note_Counter_Party, NULL as
    Note_Premium_PC  ';
       v_SelectSQL := v_SelectSQL || '  , NI.Issuer_Name, IP.Issuer_Id, IP.Broad_Cash, IP.Odd_Cash, IP.Account_Note, IP.Rounding, IP.Decimal_Truncate, IP.Misc1 as Recidual_YN, NM.Note_Issuer_Type, NM.Target_Coupon, C_Fixing_Frequency as C_Fixing_Frequency, NM.Callable_Frequency as Callable_Frequency, NM.Strike_Price_Percentage as C_Note_Strike_PC, NM.NM_Airbag_PC as  Airbag_PC, C_Note_Barrier_PC as C_Note_Barrier_PC, TM.Template_Name, ''Product'' as Record_Type, NM.C_Settlement_Frequency, NM.Coupon_Frequency, NM.NM_Fixing_Source as Note_Fixing_Source, NM.Order_Entry_Type, (nvl(NM.Minimum_Issue_Size,0) - nvl(T2.Confirmed_Amount,0)) as Remaining_Launch_Amount, NM.C_Fixing_Start_Point, NM.C_Fixing_End_Point, NM.Order_Entry_Type, SC.Scheme_Alias, SC.Scheme_Name, CM.CM_ID, CM.CM_Name as Counterparty_Name, NM.NM_Other_Features as Other_Features, NM.Strike_Price_Percentage as Accrual_Strike, NM.NM_KnockIn as KnockIn, NM.NM_Airbag_Type, NM.NM_Put_strike as Put_Strike, NM.NM_Accrual_Strike,
    NM.NM_Counterparty_Upfront,  NM.Price_Updated_YN as Prices_Updated_YN, AD.Code as Asset_Name,NULL as KO_FREQ_TYPE, NM.Daily_Accumalation_Equities, NM.MaxNoAcc_days, NM.Guaranteed_Days, NM.Leverage_ratio, NM.NORM_IF, NM.NORM_PAIR, NM.NORM_FXRate ';
       v_SelectSQL := v_SelectSQL || ' from ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName|| '.Note_Master NM  ';
       v_SelectSQL := v_SelectSQL || 'Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Issuer_Master NI ';
          v_SelectSQL := v_SelectSQL || ' On NM.Issuer = (case when  ISNUMERIC(NM.Issuer) = 0  then  cast (NI.Issuer_Name as nvarchar2(25))  else  cast(NI.Issuer_Id as nvarchar2(25)) end )';     
       v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Note_Order_Product NOP ';
       v_SelectSQL := v_SelectSQL || ' On NOP.Note_Master_ID = NM.Note_Master_ID';
       v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_DefinitionDBName||'.AssetDef AD ';
       v_SelectSQL := v_SelectSQL || ' On AD.Code = NM.Asset';
         v_SelectSQL := v_SelectSQL || ' AND AD.TypeAsset  = substr(NM.Note_Asset_Class,1,2) ';
       v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Issuer_Parameter IP ';
          v_SelectSQL := v_SelectSQL || ' On NM.Issuer = (case when  ISNUMERIC(NM.Issuer) = 0  then  cast (IP.Issuer_Name as nvarchar2(25))  else  cast(IP.Issuer_Id as nvarchar2(25)) end )';
       v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Template_Master TM ';
       v_SelectSQL := v_SelectSQL || ' On  TM.Template_Id =  NM.Template_ID ';
       v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Scheme_Codes SC ';
       v_SelectSQL := v_SelectSQL || ' On  SC.Scheme_Alias =  NM.Type';     
       v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Counterparty_Master CM ';
       v_SelectSQL := v_SelectSQL || ' On  CM.CM_ID =  NM.Counterparty';     
          v_SelectSQL := v_SelectSQL || ' Left Outer Join      ';
       v_SelectSQL := v_SelectSQL || ' ( ';
       v_SelectSQL := v_SelectSQL || ' Select Note_master_ID, sum(Nominal_Amt) as Unwind_Amount from ';
       v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Note_Deals ';
       v_SelectSQL := v_SelectSQL || ' where Prematurity_Date IS NOT NULL';
       v_SelectSQL := v_SelectSQL || ' AND (UPPER(Deletion_Reason ) = ''PART REDEMPTION'' or UPPER(Deletion_Reason ) = ''FULL REDEMPTION'')';
       v_SelectSQL := v_SelectSQL || ' Group by Note_master_ID ';
       v_SelectSQL := v_SelectSQL || ' ) ND ';
       v_SelectSQL := v_SelectSQL || ' On  ND.Note_Master_ID =  NM.Note_Master_ID';
    if  (v_Filter_FilledStatus = ' ' OR UPPER(v_Filter_FilledStatus) = 'ALL' ) then
          v_SelectSQL := v_SelectSQL || ' ';
       else
          v_SelectSQL := v_SelectSQL || ' AND NOP.Filled_Status IN (' || v_Filter_FilledStatus  || ')';
       end if;                         
         --AND NOP.Internal_Counterparty = 'DEFAULT''
       if(SUBSTR(to_char(v_Filter_Internal_Counterparty),1,4000)= ' ')  then
          v_SelectSQL := v_SelectSQL || ' ';
       else
          v_SelectSQL := v_SelectSQL || ' AND NOP.Internal_Counterparty IN (' || v_Filter_Internal_Counterparty || ')';
       end if;                    
         --SET @SelectSQL = @SelectSQL + ' --Filter--'
       v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN ';
       v_SelectSQL := v_SelectSQL || ' (';
       v_SelectSQL := v_SelectSQL || '   select Note_Master_ID, sum(Nominal_Amount) As Confirmed_Amount, sum(No_Of_Shares)  As Confirmed_Shares  ';
       v_SelectSQL := v_SelectSQL || '   from '||v_CommonDBName||'.Note_Order_RM  ';
       v_SelectSQL := v_SelectSQL || '   Where substr(UPPER(Order_Status_Flag),1,6) = ''YYYYYY'' AND substr(substr(UPPER(Order_Status_Flag),1,7),-1,1) = ''N'' ';
       v_SelectSQL := v_SelectSQL || '   group by  Note_Master_ID';
       v_SelectSQL := v_SelectSQL || ' ) T2';
       v_SelectSQL := v_SelectSQL || ' ON T2.Note_Master_ID = NM.Note_Master_ID';
       v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN';
       v_SelectSQL := v_SelectSQL || ' (';
       v_SelectSQL := v_SelectSQL || '   Select ND.Note_Master_ID, sum(ND.Nominal_Amt) As Live_Deals ';
       v_SelectSQL := v_SelectSQL || '   from '||v_CommonDBName||'.Note_Deals ND  ';
       v_SelectSQL := v_SelectSQL || '   where ND.Active_YNFlag = ''Y'' ';
       v_SelectSQL := v_SelectSQL || '   group by  Note_Master_ID';
       v_SelectSQL := v_SelectSQL || ' ) T3';
       v_SelectSQL := v_SelectSQL || ' ON T3.Note_Master_ID = NM.Note_Master_ID';
       v_SelectSQL := v_SelectSQL || '  LEFT OUTER JOIN';
       v_SelectSQL := v_SelectSQL || '  (';
       v_SelectSQL := v_SelectSQL || '  SELECT NH_Note_Master_ID,';
       v_SelectSQL := v_SelectSQL || '  (CAST(SUM(Hedged_Nominal_Buy) AS BINARY_FLOAT) -CAST(SUM(Hedged_Nominal_Sell) AS BINARY_FLOAT))  Net_Trade_Hedged,';
       v_SelectSQL := v_SelectSQL || '  (CAST(SUM(Outstanding_Nominal_BUY) AS BINARY_FLOAT) -CAST(SUM(Outstanding_Nominal_SELL) AS BINARY_FLOAT))  Net_Trade_Outstanding,';
       v_SelectSQL := v_SelectSQL || '  SUM(Hedged_Nominal_BUY) AS Hedged_Nominal_BUY,';
       v_SelectSQL := v_SelectSQL || '  SUM(Hedged_Nominal_SELL) AS Hedged_Nominal_SELL,';
       v_SelectSQL := v_SelectSQL || '  SUM(Outstanding_Nominal_BUY) AS Outstanding_Nominal_BUY,';
       v_SelectSQL := v_SelectSQL || '  SUM(Outstanding_Nominal_SELL) As Outstanding_Nominal_SELL';
       v_SelectSQL := v_SelectSQL || '  From';
       v_SelectSQL := v_SelectSQL || '  (';
       v_SelectSQL := v_SelectSQL || '  SELECT NH_Note_Master_ID,';
       v_SelectSQL := v_SelectSQL || '  SUM(NH_Hedged_Nominal) AS Hedged_Nominal_BUY, 0 AS Hedged_Nominal_SELL,';
       v_SelectSQL := v_SelectSQL || '  SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_BUY, 0 AS Outstanding_Nominal_SELL';
       v_SelectSQL := v_SelectSQL || '  FROM '||v_CommonDBName||'.Note_Hedge  ';
       v_SelectSQL := v_SelectSQL || '  WHERE NH_Direction = ''BUY'' ';
       v_SelectSQL := v_SelectSQL || '  GROUP BY NH_Note_Master_ID';
       v_SelectSQL := v_SelectSQL || '  Union';
       v_SelectSQL := v_SelectSQL || '  SELECT NH_Note_Master_ID,';
       v_SelectSQL := v_SelectSQL || '  0 AS Hedged_Nominal_BUY, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_SELL,';
       v_SelectSQL := v_SelectSQL || '  0 AS Outstanding_Nominal_BUY, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_SELL';
       v_SelectSQL := v_SelectSQL || '  FROM '||v_CommonDBName||'.Note_Hedge  ';
       v_SelectSQL := v_SelectSQL || '  WHERE NH_Direction = ''SELL''  ';
       v_SelectSQL := v_SelectSQL || '  GROUP BY NH_Note_Master_ID';
       v_SelectSQL := v_SelectSQL || '  ) ';
       v_SelectSQL := v_SelectSQL || '  GROUP BY NH_Note_Master_ID';
       v_SelectSQL := v_SelectSQL || '  ) BS';
       v_SelectSQL := v_SelectSQL || '  ON BS.NH_Note_Master_ID = NM.Note_Master_ID';
       v_SelectSQL := v_SelectSQL || ' Where NM.Verify_YN_Flag = ''Y'' ';
      v_SelectSQL := v_SelectSQL || ' AND NM.Active_YN_Flag = ''' || SWV_Active_YN_Flag || '''';
       if(SUBSTR(to_char(v_Filter_NoteType),1,4000) = ' ' OR UPPER(v_Filter_NoteType) = 'ALL' ) then
               v_SelectSQL := v_SelectSQL || ' ';
       else
          v_SelectSQL := v_SelectSQL || ' AND NM.Type IN (' || v_Filter_NoteType  || ')';
       end if;     
    IF UPPER(v_Entity_ID) <> 'ALL'  then
          OPEN RestrictTermsheetVisibilityByC;
          FETCH RestrictTermsheetVisibilityByC INTO v_Setting_Name,v_Default_Value,v_Config_Value;
          WHILE RestrictTermsheetVisibilityByC%FOUND   LOOP
         --2) Convert comma separated ccy (CNY,HKD,USD) string to single quote ccy with comma separated Ccy ('CNY','HKD','USD') string
             if (UPPER(v_Setting_Name) = 'RESTRICT_TERMSHEET_VISIBILITY_BY_CCY')  then
                if v_Config_Value is not null  then
              SELECT COUNT(Id_1) INTO SWV_fnc_SplitString_Id_var0 FROM TABLE(fnc_SplitString(v_Config_Value,',')) ;
                   IF (SWV_fnc_SplitString_Id_var0 > 0)  then
                        --print 'Before Single  quote separated ccy : ' + '''' + @Config_Value + ''''
                      v_Seq_Id := 0;
                      OPEN Get_RestrictCCY_List_Cursor;
                      FETCH Get_RestrictCCY_List_Cursor
                      INTO v_CCY_ID,v_CCY_Data;
                      WHILE Get_RestrictCCY_List_Cursor%FOUND   LOOP
                         if v_Seq_Id = 0  then
                            v_CCY_List := '''' || v_CCY_Data || '''';
                         else
                            v_CCY_List := v_CCY_List || ',' || '''' || v_CCY_Data || '''';
                         end if;
                         v_Seq_Id := v_Seq_Id+1;
                         FETCH Get_RestrictCCY_List_Cursor INTO v_CCY_ID,v_CCY_Data;
                      END LOOP;
                      CLOSE Get_RestrictCCY_List_Cursor;
                        --print 'After Single quote ccy : ' + @CCY_List
                      v_SelectSQL := v_SelectSQL || ' AND nvl(NM.Denomination_Ccy,NM.Currency) NOT IN (' || v_CCY_List   || ')';
                   end if;
                end if;
             end if;
    --3) Convert comma separated template (ELN,BELN,BELN_B) string to single quote template code with comma separated template ('ELN','BELN','BELN_B') string
             if (UPPER(v_Setting_Name) = 'RESTRICT_TERMSHEET_VISIBILITY_BY_SUBSCHEME')  then
                if v_Config_Value is not null then
          SELECT COUNT(Id_1) INTO SWV_fnc_SplitString_Id_var1 FROM TABLE(fnc_SplitString(v_Config_Value,',')) ;
                   IF (SWV_fnc_SplitString_Id_var1 > 0)  then
                      v_Seq_Id := 0;
                      OPEN GetRestrictTemplateListCursor;
                      FETCH GetRestrictTemplateListCursor
                      INTO v_CCY_ID,v_CCY_Data;
                      WHILE GetRestrictTemplateListCursor%FOUND 
                      LOOP
                         if v_Seq_Id = 0  then
                            v_CCY_List := '''' || v_CCY_Data || '''';
                         else
                            v_CCY_List := v_CCY_List || ',' || '''' || v_CCY_Data || '''';
                         end if;
                         v_Seq_Id := v_Seq_Id+1;
                         FETCH GetRestrictTemplateListCursor INTO v_CCY_ID,v_CCY_Data;
                      END LOOP;
                      CLOSE GetRestrictTemplateListCursor;
                   --print 'After Single quote template code: ' + @CCY_List
                      v_SelectSQL := v_SelectSQL || ' AND TM.Template_Code NOT IN (' || v_CCY_List   || ')';
                   end if;
                end if;
             end if;
             FETCH RestrictTermsheetVisibilityByC INTO v_Setting_Name,v_Default_Value,v_Config_Value;
          END LOOP;
          CLOSE RestrictTermsheetVisibilityByC;
       end if;
      if  (v_Filter_Exchange = ' ' OR UPPER(v_Filter_Exchange) = 'ALL')  then
          v_SelectSQL := v_SelectSQL || ' ';
       else
          v_SelectSQL := v_SelectSQL || ' AND NM.Exchange IN (' || v_Filter_Exchange  || ')';
       end if;                         
         --SET @SelectSQL = @SelectSQL + ' --AND NM.Issuer = 4'
      if  (v_Filter_Issuer = ' ' OR UPPER(v_Filter_Issuer) = 'ALL') then
          v_SelectSQL := v_SelectSQL || ' ';
       else
          v_SelectSQL := v_SelectSQL || ' AND NM.Issuer IN (' || v_Filter_Issuer  || ')';
       end if;     
          if  v_Filter_Product_Category    = ' '  then
          v_SelectSQL := v_SelectSQL || ' ';
       else
          v_SelectSQL := v_SelectSQL || ' AND UPPER(NM.Note_Issuer_Type) IN (''' || v_Filter_Product_Category  || ''')';
       end if;          
       if UPPER(v_DateToFilter) = 'NA'  then
          v_SelectSQL := v_SelectSQL || ' ';
       else
          if UPPER(v_DateToFilter) = 'CLOSE_DATE'  then
             v_SelectSQL := v_SelectSQL || ' AND to_char( '|| v_DateToFilter || ') >= to_date(''' || v_Filter_ToDate ||  ''');
                             -- AND convert(smalldatetime,''' || v_Filter_ToDate || ''',106) ';
          else
             v_SelectSQL := v_SelectSQL || ' AND to_char(''' || v_DateToFilter || ''') BETWEEN to_date(''' || v_Filter_FromDate ||  ''') AND to_date(''' || v_Filter_ToDate || ''') ';
          end if;
       end if;
       v_SelectSQL := v_SelectSQL || ' Order by NM.Product_Name';
       SWV_VarStr := v_SelectSQL;
       DBMS_OUTPUT.PUT_LINE(SWV_VarStr);
       EXECUTE IMMEDIATE SWV_VarStr;
       IF SQLCODE <> 0  then
          GOTO ERROR_HANDLER;
       end if;
       IF SQL%rowcount > 0  then
          COMMIT;
          SWV_TRANCOUNT := SWV_TRANCOUNT -1;
       end if;     --Commit Transaction
       v_ErrorNumber := SQLCODE;
       RETURN;
       << ERROR_HANDLER >> v_ErrorNumber := SQLCODE;
       ROLLBACK;
       SWV_TRANCOUNT := 0;     --Rollback Transaction
       RETURN;
    END;Please suggest something. Thanks
    Edited by: BluShadow on 30-Nov-2011 11:00
    added {noformat}{noformat} tags for formatting of code.  Please read {message:id=9360002} to learn to do this yourself in future.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Connecting to the database sample_adf_finiq_common.
    Select NM.Note_Master_Id, NM.Product_Name, NM.Template_ID, NM.Template_Sr_No, NM.Asset, NM.Exchange, NM.Type, NM.Currency , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.PriceList_YN = 'Y') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.PriceList_YN = 'Y') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost , NM.Minimum_Issue_Size, NM.Maximum_Issue_Size, NM.Minimum_Tolerence_Amount, NM.Maximum_Tolerence_Amount, NM.Trigger_Amount_Warning, nvl(NM.PerUnit_Equivalent_Amount,1) as PerUnit_Equivalent_Amount, NM.Active_YN_Flag, NM.Verify_YN_Flag , NM.Tranche_YN_Flag, NM.Launch_Date, NM.Open_Date, NM.Close_Date, NM.PreHedged_YN, NM.Created_By, NM.Created_At, NM.Verified_At, NM.Verified_By, NM.ISIN, NM.Issuer , NM.Product_Catagory as Product_Category, NM.Note_Issuer_Type as Issuer_Category, NM.Series_No as Series_No, NM.Minimum_Investment_Amount , NOP.LastTimeWhenProductModified,(NOP.Nominal_Amount - nvl(ND.Unwind_Amount,0) ) as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty ,T2.Confirmed_Amount, T2.Confirmed_Shares , T3.Live_Deals , BS.Net_Trade_Hedged, BS.Net_Trade_Outstanding, BS.Hedged_Nominal_BUY, BS.Hedged_Nominal_SELL, BS.Outstanding_Nominal_BUY, BS.Outstanding_Nominal_SELL , ( case When UPPER(NM.PreHedged_YN) = 'Y' Then 'Launched' When ((NM.Maturity_Date IS NOT NULL) AND to_date(NM.Maturity_Date) <= to_date(sysdate)) Then 'Matured' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NOT NULL) Then 'Launched' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= NM.Minimum_Issue_Size) AND to_date(Close_Date) > to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)= to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)< to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NOT NULL AND (T2.Confirmed_Amount >= NM.Trigger_Amount_Warning )) Then 'Warning Trigger Reached' Else 'Not Ready' End)Launch_Status , NI.Issuer_Code , (nvl(NOP.Nominal_Amount,0) - nvl(T2.Confirmed_Amount,0)) as Unconfirmed_Amount, NM.Upfront as Upfront, case when UPPER(NM.PreHedged_YN) = 'Y' THEN 0 else (nvl(T2.Confirmed_Amount,0) - nvl(BS.Net_Trade_Hedged,0)) end as ReadyToHedge , NOP.Hard_Margin as Margin_Amount, NM.YearBasis as YearBasis, NM.Note_Product_Rating as Equity_Risk_Score, AD.Equity_Asset_Class , NM.Note_Product_Rating as Product_Rating, NOP.PO_ID, AD.LotSize as Lot_Size, NM.Max_Orders_Per_Product as MAX_Orders, NOP.Order_Count as Current_Order_Count, nvl(NM.Denomination_Ccy,NM.Currency) as Denomination_Ccy, NM.Note_Scheme_Type as Underlying_Type, NM.Note_Asset_Class as Asset_Class, NULL as Product_Created_YN, NULL as Product_Created_ID, ( (case when NM.Note_Order_Type = '' then N'Market' else NM.Note_Order_Type end ) ) as Order_Type, NOP.Spot_Price, NM.Note_Price_Link, NOP.Strike_Price, NVL(NM.C_Fixing_Frequency,'Atmaturity') as Fixing_Frequency, NM.Document_Uploaded_YN, NM.Document_Uploaded_At, NM.Document_Uploaded_By, NM.Document_File_Name, NM.Document_File_Extension, NM.Document_File_Path, NM.CutOff_Time, NM.Soft_Tenor, NM.NM_Sn_Code_All, NULL as Note_Price_Source, AD.LongName, NVL(NM.Pricelist_YN,'N') as Pricelist_YN, AD.AlternateIdentifierAlias as Underlying, NM.Note_Issuer_Date_Offset, NM.Counterparty as Note_Counter_Party, NULL as
    Note_Premium_PC , NI.Issuer_Name, IP.Issuer_Id, IP.Broad_Cash, IP.Odd_Cash, IP.Account_Note, IP.Rounding, IP.Decimal_Truncate, IP.Misc1 as Recidual_YN, NM.Note_Issuer_Type, NM.Target_Coupon, C_Fixing_Frequency as C_Fixing_Frequency, NM.Callable_Frequency as Callable_Frequency, NM.Strike_Price_Percentage as C_Note_Strike_PC, NM.NM_Airbag_PC as Airbag_PC, C_Note_Barrier_PC as C_Note_Barrier_PC, TM.Template_Name, 'Product' as Record_Type, NM.C_Settlement_Frequency, NM.Coupon_Frequency, NM.NM_Fixing_Source as Note_Fixing_Source, NM.Order_Entry_Type, (nvl(NM.Minimum_Issue_Size,0) - nvl(T2.Confirmed_Amount,0)) as Remaining_Launch_Amount, NM.C_Fixing_Start_Point, NM.C_Fixing_End_Point, NM.Order_Entry_Type, SC.Scheme_Alias, SC.Scheme_Name, CM.CM_ID, CM.CM_Name as Counterparty_Name, NM.NM_Other_Features as Other_Features, NM.Strike_Price_Percentage as Accrual_Strike, NM.NM_KnockIn as KnockIn, NM.NM_Airbag_Type, NM.NM_Put_strike as Put_Strike, NM.NM_Accrual_Strike,
    NM.NM_Counterparty_Upfront, NM.Price_Updated_YN as Prices_Updated_YN, AD.Code as Asset_Name,NULL as KO_FREQ_TYPE, NM.Daily_Accumalation_Equities, NM.MaxNoAcc_days, NM.Guaranteed_Days, NM.Leverage_ratio, NM.NORM_IF, NM.NORM_PAIR, NM.NORM_FXRate from Sample_ADF_finiq_Common.Note_Master NM Left Outer Join Sample_ADF_finiq_Common.Issuer_Master NI On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (NI.Issuer_Name as nvarchar2(25)) else cast(NI.Issuer_Id as nvarchar2(25)) end ) Left Outer Join Sample_ADF_finiq_Common.Note_Order_Product NOP On NOP.Note_Master_ID = NM.Note_Master_ID Left Outer Join Sample_ADF_finiq_Common.AssetDef AD On AD.Code = NM.Asset AND AD.TypeAsset = substr(NM.Note_Asset_Class,1,2) Left Outer Join Sample_ADF_finiq_Common.Issuer_Parameter IP On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (IP.Issuer_Name as nvarchar2(25)) else cast(IP.Issuer_Id as nvarchar2(25)) end ) Left Outer Join Sample_ADF_finiq_Common.Template_Master TM On TM.Template_Id = NM.Template_ID Left Outer Join Sample_ADF_finiq_Common.Scheme_Codes SC On SC.Scheme_Alias = NM.Type Left Outer Join Sample_ADF_finiq_Common.Counterparty_Master CM On CM.CM_ID = NM.Counterparty Left Outer Join      ( Select Note_master_ID, sum(Nominal_Amt) as Unwind_Amount from Sample_ADF_finiq_Common.Note_Deals where Prematurity_Date IS NOT NULL AND (UPPER(Deletion_Reason ) = 'PART REDEMPTION' or UPPER(Deletion_Reason ) = 'FULL REDEMPTION') Group by Note_master_ID ) ND On ND.Note_Master_ID = NM.Note_Master_ID AND NOP.Internal_Counterparty IN (1) LEFT OUTER JOIN ( select Note_Master_ID, sum(Nominal_Amount) As Confirmed_Amount, sum(No_Of_Shares) As Confirmed_Shares from Sample_ADF_finiq_Common.Note_Order_RM Where substr(UPPER(Order_Status_Flag),1,6) = 'YYYYYY' AND substr(substr(UPPER(Order_Status_Flag),1,7),-1,1) = 'N' group by Note_Master_ID ) T2 ON T2.Note_Master_ID = NM.Note_Master_ID LEFT OUTER JOIN ( Select ND.Note_Master_ID, sum(ND.Nominal_Amt) As Live_Deals from Sample_ADF_finiq_Common.Note_Deals ND where ND.Active_YNFlag = 'Y' group by Note_Master_ID ) T3 ON T3.Note_Master_ID = NM.Note_Master_ID LEFT OUTER JOIN ( SELECT NH_Note_Master_ID, (CAST(SUM(Hedged_Nominal_Buy) AS BINARY_FLOAT) -CAST(SUM(Hedged_Nominal_Sell) AS BINARY_FLOAT)) Net_Trade_Hedged, (CAST(SUM(Outstanding_Nominal_BUY) AS BINARY_FLOAT) -CAST(SUM(Outstanding_Nominal_SELL) AS BINARY_FLOAT)) Net_Trade_Outstanding, SUM(Hedged_Nominal_BUY) AS Hedged_Nominal_BUY, SUM(Hedged_Nominal_SELL) AS Hedged_Nominal_SELL, SUM(Outstanding_Nominal_BUY) AS Outstanding_Nominal_BUY, SUM(Outstanding_Nominal_SELL) As Outstanding_Nominal_SELL From ( SELECT NH_Note_Master_ID, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_BUY, 0 AS Hedged_Nominal_SELL, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_BUY, 0 AS Outstanding_Nominal_SELL FROM Sample_ADF_finiq_Common.Note_Hedge WHERE NH_Direction = 'BUY' GROUP BY NH_Note_Master_ID Union SELECT NH_Note_Master_ID, 0 AS Hedged_Nominal_BUY, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_SELL, 0 AS Outstanding_Nominal_BUY, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_SELL FROM Sample_ADF_finiq_Common.Note_Hedge WHERE NH_Direction = 'SELL' GROUP BY NH_Note_Master_ID ) GROUP BY NH_Note_Master_ID ) BS ON BS.NH_Note_Master_ID = NM.Note_Master_ID Where NM.Verify_YN_Flag = 'Y' AND NM.Active_YN_Flag = 'Y' AND UPPER(NM.Note_Issuer_Type) IN ('Internal') AND to_char('16-oct-11') BETWEEN to_date('15-oct-11') AND to_date('17-oct-11') Order by NM.Product_Name
    V_ERRORNUMBER = 0
    Process exited.
    Disconnecting from the database sample_adf_finiq_common.
    here v_errornumber=0 is the output when i run it in oracle sql developer.

Maybe you are looking for