Rownum and order by as parameter

i want a procedure that will accept the 'from' and 'to' parameter (rownum) for paginaton as well as the order by column also as a parameter( the order by changes based on the parameter) , and my query is using multiple table which doesnt have Unique keys, the pagination is not working poperly at that time..
please have a look in to the procedure..
CREATE OR REPLACE Procedure P_pagination
(cur out sys_refcursor,end1 number,start1 number,ordr number)
as
Var_sql varchar2(4000);
begin
var_sql := ' Select * '||
          ' From '||
          ' (select rownum rwnum,aa.* from ' ||
          ' (select ti.a,t2.a,t3.a,t4.b from t1,t2,t3,t4 where < all the joins> order by '||ordr||' )aa'||
          ' where rownum <='|| end1 ||') ' ||
          ' where rwnum >='|| start1 ;
open cur for var_sql;
end ;
/

If you don't specify explicit ORDER BY clause
Oracle wont guarantee the order of the sort. You specify ORDER BY ID , but
not ORDER BY ID, <<something>> , so you have unrepeatable results. Your order by ID but don't order inside ID. Look:
SQL> select *
  2  from
  3  (select a.*, rownum rnum
  4  from
  5  (select id, data
  6  from t
  7  order by id) a
  8  where rownum <= 150
  9  )
10  where rnum >= 148
11  /
        ID       DATA       RNUM
         0         34        148
         0         54        149
         0         81        150
SQL> select *
  2  from
  3  (select a.*, rownum rnum
  4  from
  5  (select id, data
  6  from t
  7  order by id) a
  8  where rownum <= 151
  9  )
10  where rnum >= 148
11  /
        ID       DATA       RNUM
         0         28        148
         0         34        149
         0         54        150
         0         81        151
SQL> select *
  2  from
  3  (select a.*, rownum rnum
  4  from
  5  (select id, data
  6  from t
  7  order by id, rowid) a
  8  where rownum <= 150
  9  )
10  where rnum >= 148
11  /
        ID       DATA       RNUM
         0         24        148
         0         21        149
         0         35        150
SQL> select *
  2  from
  3  (select a.*, rownum rnum
  4  from
  5  (select id, data
  6  from t
  7  order by id, rowid) a
  8  where rownum <= 151
  9  )
10  where rnum >= 148;
        ID       DATA       RNUM
         0         24        148
         0         21        149
         0         35        150
         0         68        151Rgds.

Similar Messages

  • Trouble with subquery and rownum and ordering

    I'm having trouble making this subquery work. The basic idea is that the web app will show only so many rows of results on the page, but right now I'm just playing around in SQL*Plus. The address book holds mixed case, so in order to sort by name properly I need to use UPPER to ignore case sensitivity. This SQL statement works fine for me:
    select addressbookid from addressbook where addressbookid like '905430931|%' order by upper(addressbookid);I know that if you mention ROWNUM in the WHERE clause, you're referring to the row numbers of the ResultSet that Oracle returns. How do I use both ORDER BY UPPER(ADDRESSBOOKID) and WHERE ROWNUM > 25 AND ROWNUM <= 50? I figured a subquery would do it, but I can't write a correct one that does it! Below are my 2 attempts with the errors, and then I just tried to play with rownum:
    SQL> select addressbookid from addressbook where addressbookid in (select addressbookid from address book where addressbookid like '905430931|%' order by upper(addressbookid));
    select addressbookid from addressbook where addressbookid in (select addressbookid from addressbook
    ERROR at line 1:
    ORA-00907: missing right parenthesis
    SQL> select addressbookid from addressbook where addressbookid in upper(select addressbookid from addressbook where addressbookid like '905430931|%');
    select addressbookid from addressbook where addressbookid in upper(select addressbookid from address
    ERROR at line 1:
    ORA-00936: missing expression
    SQL> select addressbookid from addressbook where addressbookid like '905430931|%' and rownum > 25 and rownum <= 50 order by upper(addressbookid);
    no rows selected
    SQL> select addressbookid from addressbook where addressbookid like '905430931|%' and rownum > 25 and rownum <= 50;
    no rows selectedLike I said, if I can get a working subquery, then I'd like to attach that restriction on the rownum stuff. I'm wondering if it will be a problem trying to get the ordering to happen and then the rownum restriction after that, and all in the same query...
    Btw, we've made all the table and column names in our database uppercase, so that shouldn't matter.

    This is probably the most efficient way ...
    select addressbookid
    from
       select addressbookid,
       rownum rn
       from
          select addressbookid
          from addressbook
          where addressbookid like '905430931|%'
          order by addressbookid
       where rownum <= 50
    where rn > 25

  • Combination of rownum and order by in where

    Hi friends
    This is the simple query pl. have a look.
    SQL> select distinct sal from emp
    2 order by sal desc;
    SAL
    5000
    3000
    2975
    2850
    2450
    1600
    1500
    1300
    1250
    1100
    950
    SAL
    800
    500
    200
    14 rows selected.
    Now I want to list only top 5 salaries from this with sql statement
    like
    5000
    3000
    2975
    2850
    2450

    This feature is available from oracle's 8.1.5 onwards
    Example with an Inline View
    Suppose we have a table emp which contains empname and sal. then using Inline View we can write sql like this:
    SELECT * FROM (SELECT * FROM emp ORDER BY sal DESC)
    WHERE ROWNUM < 5;
    here u will get the top 4 salaries.if u want to avoid same sal then use distict also.If u want 2nd maxima then put rownum=2;
    I think u r tried with oracle 8.0 or below versions.test with oracle 8i or above.Then u will get the result.
    Best wishes
    SHINOY.V.V.
    KODUNGALLUR,
    THRISSUR
    KERALA
    INDIA
    ( WORKING IN[b] IBM BANGALORE)
    Kerala,Thrissur,Kodungallur)
    IBM Bangalore

  • How to : rownum and order by in select statement

    Say I have a select statement with additional 'order by' clause.
    The result set I want prepended by the rownum column.
    But, and here comes the flaw, I want the rownum for the already ordered result set
    not the unordered.
    An example:
    select firstname, lastname from myTable order by lastname;
    When I add the rownum to the select clause,
    'select rownum, firstname, lastname from myTable order by lastname;'
    I might get something like:
    20 Mike Adams
    13 Nina Bravo
    1 Tom Charlie
    But I want the following result:
    1 Mike Adams
    2 Nina Bravo
    3 Tom Charlie
    I could now
    'Select rownum, lastname, firstname from (select firstname, lastname from myTable order by lastname);
    But I guess there is a better way!?!
    which is the best way to accomplish that?
    Thanks for your advice!

    >
    'Select rownum, lastname, firstname from (select firstname, lastname from myTable order by lastname)
    >
    Well if you ask me there is very little difference between this query and the above query
    select rownum, lastname, firstname from mytable;Because rownum is assigned before the order by. The difference is in your query you are assigning a rownum to an ordered resultset but still there is no guarantee oracle is going to read the data in an ordered fashion. In the second query rownum is assigned to an unordered resultset. Again it is the samething. So if you want to guarantee it then I will go for the following option
    select row_number() over(order by lastname) rn, lastname, firstname from mytable
    order by lastnameAlso check this link.
    http://www.oracle.com/technology/oramag/oracle/07-jan/o17asktom.html
    Regards
    Raj
    Edited by: R.Subramanian on Jan 13, 2009 6:20 AM

  • ROWNUM and order of elements in PL/SQL collection

    I have collection col of type tt_number is table of number.
    For example, values in collection are:
    col[1] = 123
    col[2] = -123
    col[3] = 999
    I'm running such query:
    select ROWNUM as "rn", column_value as "val"
    from table(col)
    Could I be sure, that my results always will look like:
    RN VAL
    1 123
    2 -123
    3 999
    Does ROWNUM equals to collection index?
    As I know, when querying tables, ROWNUM doesn't guarantee such things (unless querying "ordered by" subquery). But how about queries to collections?
    Regards, Dmitry Kuitskiy, 3-T Ltd, Kiev, Ukraine

    These Tom Kyte's threads can help you:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:1193224283514449959::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:4447489221109
    http://asktom.oracle.com/pls/ask/f?p=4950:8:1193224283514449959::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:3008276249843
    Rgds.

  • Question about order by and rownum and subqueries.

    Can you explain why test 4 below results as it results- with returning no rows?
    Identificator "PKG_INTRA_CUSTOMER_SEARCH.NAME" is a package function, which returns value from a variable declared in package body, the function returns value 'e%'.
    Please note that tests 1-3 all returned data, but test 4 didn't. Why? My porpouse is that test 4 would also return data.
    1. Query without "rownum" and with "Order by" returns 2 records:
    select q.*--, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                order by c.NAME, c.ID
                ) q
    10020     Ees Nimi     37810010237     e%
    10040     ewewrwe werwerwer          e%2. Query with "rownum" and without "Order by" returns 2 records:
    select q.*, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                --order by c.NAME, c.ID
                ) q
    10020     Ees Nimi     37810010237     e%
    10040     ewewrwe werwerwer          e%3.Query without "rownum" and with "Order by" returns 2 records:
    select q.*--, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                order by c.NAME, c.ID
                ) q
    10020     Ees Nimi     37810010237     e%
    10040     ewewrwe werwerwer          e% 4. Query with "rownum" and with "Order by" returns 0 records:
    select q.*, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                order by c.NAME, c.ID
                ) q

    Hi,
    please reproduce the question in your test database with script below.
    My general question is that wht Test5 below returns only 1 row, but Test5 returns 3 rows.
    The difference between those two tests is only that one has "order by" clause, the other doesn't have.
    I need the "order by" clause to stay, but seems like it is not allowed.
    CREATE OR REPLACE
    PACKAGE PACKAGE1 AS
    function NAME return varchar2;
    END PACKAGE1;
    CREATE OR REPLACE
    PACKAGE body PACKAGE1 AS
    function NAME return varchar2
    is
    begin
       return 'e%';
    end NAME;
    END PACKAGE1;
    select PACKAGE1.name from dual--e%
    create table Tbl AS
       (SELECT 'e2b' Col1, 'A' Col2, 'AA' Col3 FROM dual
       UNION
       SELECT 'e3b', 'B','BB' FROM dual
    --Test5:  
    select q.*, rownum pos, PACKAGE1.name f         
             from
                select c.col1,
                   c.col2,
                   c.col3     
                from Tbl c  
                where 1=1 and  lower(c.col1) like PACKAGE1.name                      
                order by c.col2, c.col1
                ) q                               
                union all
             select '111' , '111' , '111' , 0 pos, PACKAGE1.name f from dual   --return 1 row
    --Test6
    select q.*, rownum pos, PACKAGE1.name f         
             from
                select c.col1,
                   c.col2,
                   c.col3     
                from Tbl c  
                where 1=1 and  lower(c.col1) like PACKAGE1.name                      
                --order by c.col2, c.col1
                ) q                               
                union all
             select '111' , '111' , '111' , 0 pos, PACKAGE1.name f from dual   --return 3 rowsEdited by: CharlesRoos on Feb 17, 2010 5:30 AM

  • Problem with nested select in procedure and order by

    Hi,
    I have this procedure:
    CREATE OR REPLACE PROCEDURE Mkt_Flussi_Giornalieri2
    ( idGruppo IN VARCHAR2
    , dataInizio IN DATE
    , dataFine IN DATE
    , startRow IN NUMBER
    , endRow IN NUMBER
    , column_order in varchar2
    --, order_name in varchar2
    , recordsetCursor OUT SYS_REFCURSOR
    , countRow OUT NUMBER
    ) IS
    order_clause varchar2(200) := ' ';
    sql_stm varchar2(32000);
    BEGIN
    IF column_order IS NOT NULL
    THEN
    order_clause := column_order;
    ELSE
    order_clause := ' stato DESC ';
    END IF;
    dbms_output.put_line('clausola:'||order_clause);
    sql_stm:='
         SELECT idflusso, descrizioneFlusso, dataRiferimento, strDataRiferimento,
            stato,  dataElaborazione, ultimoMessaggio, livello, utentiRiferimento,
            exec_seq, provider_description, log_info FROM
      (SELECT idflusso, descrizioneFlusso, dataRiferimento, strDataRiferimento,
            stato,  dataElaborazione, ultimoMessaggio, livello, utentiRiferimento,
            exec_seq, provider_description, log_info FROM
      (SELECT
    temp.flow_id AS idFlusso,
    MKT_FLOW.flow_id || '' - '' || MKT_FLOW.flow_description || ''('' || temp.exec_seq || '')'' AS descrizioneFlusso,
    TO_DATE(temp.date_id,''yyyymmddhh24miss'') AS dataRiferimento,
    TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''dd/mm/yyyy'')||'' h. ''||TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''hh24:mi'') AS strDataRiferimento,
    temp.status AS stato, temp.end_time AS dataElaborazione, DECODE(temp.status,3, ERROR_DESC, 1, TRACE_DES) AS ultimoMessaggio,
    DECODE(temp.status,3, error_level, 1, fk_trace_level) AS livello,
    Get_Group_Description(MKT_FLOW.flow_id) AS utentiRiferimento, temp.exec_seq AS exec_seq, mp.provider_description,
                             mp.provider_link, mfc.log_info
    FROM (
      SELECT v.*, tr.TRACE_ID, tr.TRACE_DES , tr.trace_date, tr.fk_trace_level, e.ERROR_ID, e.ERROR_CODE, NVL(e.ERROR_DESC, er.ERROR_DESC) AS ERROR_DESC, e.error_date, e.error_level,
      MIN(e.error_id) OVER (PARTITION BY e.fk_exec_seq) eid,
      MAX(tr.trace_id) OVER (PARTITION BY tr.fk_exec_seq) tid
      FROM (
        SELECT fc.*, MAX(exec_seq) OVER (PARTITION BY flow_id, flow_frequency, n_run, date_id) exsq
        FROM mkt_flow_conf_view fc
        WHERE TRUNC(end_time) >= :1
          AND TRUNC(end_time) <= :2
      ) v, MKT_ERROR er, MKT_FLOW_ERROR e, MKT_FLOW_TRC tr
      WHERE v.exec_seq        = v.exsq
        AND e.fk_exec_seq (+) = v.exec_seq
        AND tr.fk_exec_seq (+) = v.exec_seq
        AND er.error_id (+) = e.error_code
    ) temp
    INNER JOIN MKT_FLOW
    ON MKT_FLOW.flow_id = temp.flow_id AND MKT_FLOW.n_run = temp.n_run AND MKT_FLOW.flow_frequency = temp.flow_frequency
    INNER JOIN MKT_FLOW_GROUP ON MKT_FLOW_GROUP.flow_id = MKT_FLOW.flow_id
    LEFT OUTER JOIN
                             (SELECT DISTINCT flow_id, log_info
                                         FROM mkt_flow_conf) mfc
                             ON mkt_flow.flow_id = mfc.flow_id
                             , mkt_provider mp
    WHERE NVL(error_id, -1) = NVL(eid, -1)
      AND NVL(trace_id, -1) = NVL(tid, -1)
      AND MKT_FLOW_GROUP.group_id=:3
      AND NVL (mkt_flow.fk_provider_id, '' '') =
                                                         NVL (mp.provider_id, '' '') )
      WHERE ROWNUM <= :4
      MINUS
      (SELECT idflusso, descrizioneFlusso, dataRiferimento, strDataRiferimento,
            stato,  dataElaborazione, ultimoMessaggio, livello, utentiRiferimento,
            exec_seq, provider_description, log_info FROM
      (SELECT
    temp.flow_id AS idFlusso,
    MKT_FLOW.flow_id || '' - '' || MKT_FLOW.flow_description || ''('' || temp.exec_seq || '')'' AS descrizioneFlusso,
    TO_DATE(temp.date_id,''yyyymmddhh24miss'') AS dataRiferimento,
    TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''dd/mm/yyyy'')||'' h. ''||TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''hh24:mi'') AS strDataRiferimento,
    temp.status AS stato, temp.end_time AS dataElaborazione, DECODE(temp.status,3, ERROR_DESC, 1, TRACE_DES) AS ultimoMessaggio,
    DECODE(temp.status,3, error_level, 1, fk_trace_level) AS livello,
    Get_Group_Description(MKT_FLOW.flow_id) AS utentiRiferimento, temp.exec_seq AS exec_seq, mp.provider_description,
                             mp.provider_link, mfc.log_info
    FROM (
      SELECT v.*, tr.TRACE_ID, tr.TRACE_DES , tr.trace_date, tr.fk_trace_level, e.ERROR_ID, e.ERROR_CODE, NVL(e.ERROR_DESC, er.ERROR_DESC) AS ERROR_DESC, e.error_date, e.error_level,
      MIN(e.error_id) OVER (PARTITION BY e.fk_exec_seq) eid,
      MAX(tr.trace_id) OVER (PARTITION BY tr.fk_exec_seq) tid
      FROM (
        SELECT fc.*, MAX(exec_seq) OVER (PARTITION BY flow_id, flow_frequency, n_run, date_id) exsq
        FROM mkt_flow_conf_view fc
        WHERE TRUNC(end_time) >= :5
          AND TRUNC(end_time) <= :6
      ) v, MKT_ERROR er, MKT_FLOW_ERROR e, MKT_FLOW_TRC tr
      WHERE v.exec_seq        = v.exsq
        AND e.fk_exec_seq (+) = v.exec_seq
        AND tr.fk_exec_seq (+) = v.exec_seq
        AND er.error_id (+) = e.error_code
    ) temp
    INNER JOIN MKT_FLOW
    ON MKT_FLOW.flow_id = temp.flow_id AND MKT_FLOW.n_run = temp.n_run AND MKT_FLOW.flow_frequency = temp.flow_frequency
    INNER JOIN MKT_FLOW_GROUP ON MKT_FLOW_GROUP.flow_id = MKT_FLOW.flow_id
    LEFT OUTER JOIN
                             (SELECT DISTINCT flow_id, log_info
                                         FROM mkt_flow_conf) mfc
                             ON mkt_flow.flow_id = mfc.flow_id
                             , mkt_provider mp
    WHERE NVL(error_id, -1) = NVL(eid, -1)
      AND NVL(trace_id, -1) = NVL(tid, -1)
      AND MKT_FLOW_GROUP.group_id=:7
      AND NVL (mkt_flow.fk_provider_id, '' '') =
                                                         NVL (mp.provider_id, '' '') )
      WHERE ROWNUM <= :8
      )  ) ORDER BY :9 ' ;
    dbms_output.enable(30000);
    dbms_output.put_line(sql_stm);
    OPEN recordsetCursor FOR sql_stm USING dataInizio, dataFine, idGruppo, endRow, dataInizio, dataFine, idGruppo, startRow, order_clause;
       SELECT COUNT(*) INTO countRow FROM
      (SELECT
    temp.flow_id AS idFlusso,
    MKT_FLOW.flow_id || ' - ' || MKT_FLOW.flow_description || '(' || temp.exec_seq || ')' AS descrizioneFlusso,
    TO_DATE(temp.date_id,'yyyymmddhh24miss') AS dataRiferimento,
    TO_CHAR(TO_DATE(temp.date_id,'yyyymmddhh24miss'),'dd/mm/yyyy')||' h. '||TO_CHAR(TO_DATE(temp.date_id,'yyyymmddhh24miss'),'hh24:mi') AS strDataRiferimento,
    temp.status AS stato, temp.end_time AS dataElaborazione, DECODE(temp.status,3, ERROR_DESC, 1, TRACE_DES) AS ultimoMessaggio,
    DECODE(temp.status,3, error_level, 1, fk_trace_level) AS livello,
    Get_Group_Description(MKT_FLOW.flow_id) AS utentiRiferimento, temp.exec_seq AS exec_seq, mp.provider_description,
                             mp.provider_link, mfc.log_info
    FROM (
      SELECT v.*, tr.TRACE_ID, tr.TRACE_DES , tr.trace_date, tr.fk_trace_level, e.ERROR_ID, e.ERROR_CODE, NVL(e.ERROR_DESC, er.ERROR_DESC) AS ERROR_DESC, e.error_date, e.error_level,
      MIN(e.error_id) OVER (PARTITION BY e.fk_exec_seq) eid,
      MAX(tr.trace_id) OVER (PARTITION BY tr.fk_exec_seq) tid
      FROM (
        SELECT fc.*, MAX(exec_seq) OVER (PARTITION BY flow_id, flow_frequency, n_run, date_id) exsq
        FROM mkt_flow_conf_view fc
        WHERE TRUNC(end_time) >= dataInizio
          AND TRUNC(end_time) <= dataFine
      ) v, MKT_ERROR er, MKT_FLOW_ERROR e, MKT_FLOW_TRC tr
      WHERE v.exec_seq        = v.exsq
        AND e.fk_exec_seq (+) = v.exec_seq
        AND tr.fk_exec_seq (+) = v.exec_seq
        AND er.error_id (+) = e.error_code
    ) temp
    INNER JOIN MKT_FLOW
    ON MKT_FLOW.flow_id = temp.flow_id AND MKT_FLOW.n_run = temp.n_run AND MKT_FLOW.flow_frequency = temp.flow_frequency
    INNER JOIN MKT_FLOW_GROUP ON MKT_FLOW_GROUP.flow_id = MKT_FLOW.flow_id
    LEFT OUTER JOIN
                             (SELECT DISTINCT flow_id, log_info
                                         FROM mkt_flow_conf) mfc
                             ON mkt_flow.flow_id = mfc.flow_id
                             , mkt_provider mp
    WHERE NVL(error_id, -1) = NVL(eid, -1)
      AND NVL(trace_id, -1) = NVL(tid, -1)
      AND MKT_FLOW_GROUP.group_id=idGruppo
      AND NVL (mkt_flow.fk_provider_id, ' ') =
                                                         NVL (mp.provider_id, ' '));
    END Mkt_Flussi_Giornalieri2;
    /When I call the procedure, from java, I receive this error:
    >
    Caused by: java.sql.SQLException: invalid column index
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
         at oracle.jdbc.driver.OracleResultSetImpl.getString(OracleResultSetImpl.java:385)
         at it.edison.markettracker.dao.spring.VistaFlussiGiornalieriDaoImpl.mapRow(VistaFlussiGiornalieriDaoImpl.java:155)
         at it.edison.markettracker.dao.spring.VistaFlussiGiornalieriDaoImpl.mapRow(VistaFlussiGiornalieriDaoImpl.java:1)
         at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:92)
         at org.springframework.jdbc.core.JdbcTemplate.processResultSet(JdbcTemplate.java:1124)
         at org.springframework.jdbc.core.JdbcTemplate.extractOutputParameters(JdbcTemplate.java:1085)
         at org.springframework.jdbc.core.JdbcTemplate$5.doInCallableStatement(JdbcTemplate.java:997)
         at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:936)
         ... 26 more
    When I call the procedure from toad in this way:
    SET serveroutput ON
    DECLARE
    TROVATI SYS_REFCURSOR;
    NUMERO_TROVATI NUMBER;
    BEGIN
          DBMS_OUTPUT.ENABLE(30000);
          dbms_output.put_line('INIZIO');
          Mkt_Flussi_Giornalieri2(1, trunc(sysdate), trunc(sysdate), 100, 50, null, TROVATI, NUMERO_TROVATI);
          dbms_output.put_line('RECORD TROVATI:'||NUMERO_TROVATI);
    END; I don't receive any error messages but I don't see any message.
    Why this behaviour? I work on this procedure from the last monday. Please help me. I need to call the procedure from java.
    Thanks, bye bye.
    Edited by: Abdujaparov on Mar 5, 2009 3:44 PM

    Hi,
    I have solved the problem, I forgot a parameter in the select, so java tells the an error. But now I have another problem. The procedure doesn't execute the order by. I pass the couple column_name order_type in a string as ("provider_description desc") dinamically but the procedure doesn't execute the ordering. Why?
    The problem is in the dynamic query, I think:
    sql_stm:='
         SELECT idflusso, descrizioneFlusso, dataRiferimento, strDataRiferimento,
            stato,  dataElaborazione, ultimoMessaggio, livello, utentiRiferimento,
            exec_seq, provider_description, provider_link, log_info FROM
      (SELECT idflusso, descrizioneFlusso, dataRiferimento, strDataRiferimento,
            stato,  dataElaborazione, ultimoMessaggio, livello, utentiRiferimento,
            exec_seq, provider_description, provider_link, log_info FROM
      (SELECT
    temp.flow_id AS idFlusso,
    MKT_FLOW.flow_id || '' - '' || MKT_FLOW.flow_description || ''('' || temp.exec_seq || '')'' AS descrizioneFlusso,
    TO_DATE(temp.date_id,''yyyymmddhh24miss'') AS dataRiferimento,
    TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''dd/mm/yyyy'')||'' h. ''||TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''hh24:mi'') AS strDataRiferimento,
    temp.status AS stato, temp.end_time AS dataElaborazione, DECODE(temp.status,3, ERROR_DESC, 1, TRACE_DES) AS ultimoMessaggio,
    DECODE(temp.status,3, error_level, 1, fk_trace_level) AS livello,
    Get_Group_Description(MKT_FLOW.flow_id) AS utentiRiferimento, temp.exec_seq AS exec_seq, mp.provider_description,
                             mp.provider_link, mfc.log_info
    FROM (
      SELECT v.*, tr.TRACE_ID, tr.TRACE_DES , tr.trace_date, tr.fk_trace_level, e.ERROR_ID, e.ERROR_CODE, NVL(e.ERROR_DESC, er.ERROR_DESC) AS ERROR_DESC, e.error_date, e.error_level,
      MIN(e.error_id) OVER (PARTITION BY e.fk_exec_seq) eid,
      MAX(tr.trace_id) OVER (PARTITION BY tr.fk_exec_seq) tid
      FROM (
        SELECT fc.*, MAX(exec_seq) OVER (PARTITION BY flow_id, flow_frequency, n_run, date_id) exsq
        FROM mkt_flow_conf_view fc
        WHERE TRUNC(end_time) >= :1
          AND TRUNC(end_time) <= :2
      ) v, MKT_ERROR er, MKT_FLOW_ERROR e, MKT_FLOW_TRC tr
      WHERE v.exec_seq        = v.exsq
        AND e.fk_exec_seq (+) = v.exec_seq
        AND tr.fk_exec_seq (+) = v.exec_seq
        AND er.error_id (+) = e.error_code
    ) temp
    INNER JOIN MKT_FLOW
    ON MKT_FLOW.flow_id = temp.flow_id AND MKT_FLOW.n_run = temp.n_run AND MKT_FLOW.flow_frequency = temp.flow_frequency
    INNER JOIN MKT_FLOW_GROUP ON MKT_FLOW_GROUP.flow_id = MKT_FLOW.flow_id
    LEFT OUTER JOIN
                             (SELECT DISTINCT flow_id, log_info
                                         FROM mkt_flow_conf) mfc
                             ON mkt_flow.flow_id = mfc.flow_id
                             , mkt_provider mp
    WHERE NVL(error_id, -1) = NVL(eid, -1)
      AND NVL(trace_id, -1) = NVL(tid, -1)
      AND MKT_FLOW_GROUP.group_id=:3
      AND NVL (mkt_flow.fk_provider_id, '' '') =
                                                         NVL (mp.provider_id, '' '') )
      WHERE ROWNUM <= :4
      MINUS
      (SELECT idflusso, descrizioneFlusso, dataRiferimento, strDataRiferimento,
            stato,  dataElaborazione, ultimoMessaggio, livello, utentiRiferimento,
            exec_seq, provider_description, provider_link, log_info FROM
      (SELECT
    temp.flow_id AS idFlusso,
    MKT_FLOW.flow_id || '' - '' || MKT_FLOW.flow_description || ''('' || temp.exec_seq || '')'' AS descrizioneFlusso,
    TO_DATE(temp.date_id,''yyyymmddhh24miss'') AS dataRiferimento,
    TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''dd/mm/yyyy'')||'' h. ''||TO_CHAR(TO_DATE(temp.date_id,''yyyymmddhh24miss''),''hh24:mi'') AS strDataRiferimento,
    temp.status AS stato, temp.end_time AS dataElaborazione, DECODE(temp.status,3, ERROR_DESC, 1, TRACE_DES) AS ultimoMessaggio,
    DECODE(temp.status,3, error_level, 1, fk_trace_level) AS livello,
    Get_Group_Description(MKT_FLOW.flow_id) AS utentiRiferimento, temp.exec_seq AS exec_seq, mp.provider_description,
                             mp.provider_link, mfc.log_info
    FROM (
      SELECT v.*, tr.TRACE_ID, tr.TRACE_DES , tr.trace_date, tr.fk_trace_level, e.ERROR_ID, e.ERROR_CODE, NVL(e.ERROR_DESC, er.ERROR_DESC) AS ERROR_DESC, e.error_date, e.error_level,
      MIN(e.error_id) OVER (PARTITION BY e.fk_exec_seq) eid,
      MAX(tr.trace_id) OVER (PARTITION BY tr.fk_exec_seq) tid
      FROM (
        SELECT fc.*, MAX(exec_seq) OVER (PARTITION BY flow_id, flow_frequency, n_run, date_id) exsq
        FROM mkt_flow_conf_view fc
        WHERE TRUNC(end_time) >= :5
          AND TRUNC(end_time) <= :6
      ) v, MKT_ERROR er, MKT_FLOW_ERROR e, MKT_FLOW_TRC tr
      WHERE v.exec_seq        = v.exsq
        AND e.fk_exec_seq (+) = v.exec_seq
        AND tr.fk_exec_seq (+) = v.exec_seq
        AND er.error_id (+) = e.error_code
    ) temp
    INNER JOIN MKT_FLOW
    ON MKT_FLOW.flow_id = temp.flow_id AND MKT_FLOW.n_run = temp.n_run AND MKT_FLOW.flow_frequency = temp.flow_frequency
    INNER JOIN MKT_FLOW_GROUP ON MKT_FLOW_GROUP.flow_id = MKT_FLOW.flow_id
    LEFT OUTER JOIN
                             (SELECT DISTINCT flow_id, log_info
                                         FROM mkt_flow_conf) mfc
                             ON mkt_flow.flow_id = mfc.flow_id
                             , mkt_provider mp
    WHERE NVL(error_id, -1) = NVL(eid, -1)
      AND NVL(trace_id, -1) = NVL(tid, -1)
      AND MKT_FLOW_GROUP.group_id=:7
      AND NVL (mkt_flow.fk_provider_id, '' '') =
                                                         NVL (mp.provider_id, '' '') )
      WHERE ROWNUM <= :8
      )  ) ORDER BY :9' ;
    OPEN recordsetCursor FOR sql_stm USING dataInizio, dataFine, idGruppo, endRow, dataInizio, dataFine, idGruppo, startRow, order_clause;Where order_clause is defined so:
    IF column_order IS NOT NULL
    THEN
    order_clause := column_order;
    ELSE
    order_clause := ' stato DESC ';
    END IF;If I insert manually a name of a column and a type of ordering (asc or desc) the ordering is executed correctly. How can I solve this issue?
    Thanks, bye bye.

  • CHECK for duplicate inside a cursor and pass a ouptut parameter in sql server 2008

    Hi All,
    I am inserting a value into a table, Before inserting i am checking that record already exists or not in the target table, If its existsing i am making an entry into errorlog table and set the output parameter to 'errorlog' . This is inside the cursor, as
    il be passing multiple values. Next is I have separate query to get the new record which is not in the target table. Using EXCEPT i get the new record and i insert into a main table. after insertion i set output as 'success'. 
    Here while executing the procedure i pass a duplicate value and a new value. As it is in cursor,first it will insert into errorlog and set output parameter as 'errorlog' .Next it will insert a new record into main table and set output parameter as 'Success'.
    So on completion of the execution of the procedure i get output as success.
    But i should get as errorlog. I should get success only on no errors in the procedure. How i can i achieve this? Please help me.
    Below is my code
    IF NOT EXISTS(SELECT Beginmilepost,BeginTrackName,Endmilepost,EndTrackName
    FROM SSDB_Segment WHERE BeginMilepost>=@BegMP AND EndMilepost<=@EndMP AND SearchID = @SearchID AND Reference = 'Range')
    BEGIN
                     Declare C_Max1 Cursor FOR
    (SELECT Beginmilepost,BeginTrackName,Endmilepost,EndTrackName FROM SSDB_Segment WHERE BeginMilepost = @BegMP AND EndMilepost = @EndMP AND  BeginTrackName = @BegtrkName 
    AND EndTrackName = @EndTrkName  AND SearchID = @SearchID)
      Open C_Max1
      FETCH FROM C_MAX1 INTO @BeginMilepost,@BTrackName,@EndMilepost,@ETrackName
    WHILE(@@FETCH_STATUS=0)
    BEGIN
    IF OBJECT_ID ('tempdb..#temp') IS NOT NULL
    BEGIN
          DROP TABLE #temp
    END--IF
    Select BeginLatitude,BeginLongitude,BeginTrackName,BeginMilepost,BeginMilepostPrefix,BeginMilepostSuffix,EndLatitude,EndLongitude,EndTrackName,EndMilepost,TrainType into #temp
    FROM
    SELECT BeginLatitude= case when @BegLat = 0 THEN NULL ELSE @BegLat end ,BeginLongitude= case when @BegLong=0 THEN NULL ELSE @BEgLong end ,@BTrackName AS BeginTrackName,ROUND(@BeginMilepost ,3) AS BeginMilepost,
    BeginMilepostPrefix= CASE WHEN @BegPrefix = 'null' THEN NULL ELSE @BegPrefix END,BeginMilepostSuffix= CASE WHEN @BegSuffix  = 'null' THEN NULL ELSE @BegSuffix  END,
    EndLatitude=case when @EndLat =0 then NULL else @EndLat end,EndLongitude=case when @Endlong = 0 THEN NULL ELSE @Endlong END,@ETrackName AS EndTrackName,ROUND(@EndMilepost ,3) AS EndMilepost,@TrainType AS TrainType 
    UNION ALL
    select BeginLatitude,BeginLongitude,BeginTrackName,ROUND(BeginMilepost,3) AS BeginMilepost,BeginMilepostPrefix,BeginMilepostSuffix, EndLatitude,EndLongitude,EndTrackName,ROUND(EndMilepost,3) AS EndMilepost,TrainType from SSDB_MaximumPermissibleSpeed)data
    group by  BeginLatitude,BeginLongitude,BeginTrackName,BeginMilepost,EndLatitude,EndLongitude,EndTrackName,EndMilepost,BeginMilepostPrefix,BeginMilepostSuffix,TrainType
    having COUNT(*)>1
    SET @COUNT= (select count(*) from #temp )
    Print @COUNT
    IF @COUNT>=1
    BEGIN
     INSERT INTO ErrorLog_Asset (
                                        ErrorCode,
                                        ErrorMessage,
                                        TableName,
                                        MilepostPrefix,
                                        Milepost
    SELECT
                                     '1',
                                     'Already exists at BeginMp '+ CAST(@BeginMilepost  as varchar) +',EndMp '+ CAST(@EndMilepost as varchar) +' ,Beginlat
    '+CAST(@BegLat   as varchar)
                                     +' ,Endlat '+CAST(@EndLat   as varchar)+', BeginTrackName '+@BTrackName  +' and EndTrackName '+@ETrackName
                                     'MaximumPermissibleSpeed',
                                      CASE WHEN @BegPrefix = 'null' THEN NULL
    ELSE @BegPrefix END ,
    @BeginMilepost  
    SET @output = 'Errorlog'
    END
     IF OBJECT_ID ('tempdb..#Max') IS NOT NULL
    BEGIN
     DROP TABLE #Max
    END--IF
     Select BeginLatitude,BeginLongitude,BeginTrackName,BeginMilepost,BeginMilepostPrefix,BeginMilepostSuffix,EndLatitude,EndLongitude,EndTrackName,EndMilepost,TrainType into #Max from
           (SELECT BeginLatitude= case when @BegLat = 0 THEN NULL ELSE @BegLat end ,BeginLongitude= case when @BegLong=0 THEN NULL ELSE @BEgLong end ,@BTrackName AS BeginTrackName,ROUND(@BeginMilepost ,3)
    AS BeginMilepost,
                  BeginMilepostPrefix= CASE WHEN @BegPrefix = 'null' THEN NULL ELSE @BegPrefix END,BeginMilepostSuffix= CASE WHEN @BegSuffix  = 'null' THEN NULL ELSE @BegSuffix  END,
                  EndLatitude=case when @EndLat =0 then NULL else @EndLat end,EndLongitude=case when @Endlong = 0 THEN NULL ELSE @Endlong END,@ETrackName AS EndTrackName,ROUND(@EndMilepost ,3) AS EndMilepost,@TrainType AS TrainType 
    except
                 select BeginLatitude,BeginLongitude,BeginTrackName,ROUND(BeginMilepost,3) AS BeginMilepost,BeginMilepostPrefix,BeginMilepostSuffix, EndLatitude,EndLongitude,EndTrackName,ROUND(EndMilepost,3) AS EndMilepost,TrainType
    from SSDB_MaximumPermissibleSpeed)data
     Declare C_Max2 Cursor FOR
     Select BeginMilepost,BeginTrackName,EndMilepost,EndTrackName from #Max 
      Open C_Max2
      FETCH FROM C_Max2 INTO  @BeginMP,@BeginTrackName,@EnMP,@EnTrackName
    WHILE(@@FETCH_STATUS=0)
    BEGIN
       IF (Select COUNT(*) from tbl_Trackname )>=1
       BEGIN
     IF (@TrainType IN (SELECT TrainType  FROM SSDB_TrainType )AND (@Speed <>0) AND @BeginMP IS NOT NULL AND @BeginTrackName IS NOT NULL  AND @EnMP IS NOT NULL
     AND @Direction IN (SELECT Direction FROM SSDB_Direction) AND @EnTrackName IS NOT NULL )
     BEGIN-------------
     SET @ID = (Select MAX(MaximumpermissibleSpeedID) from SSDB_MaximumPermissibleSpeed)
    IF @COUNT =0
       BEGIN
                          INSERT INTO SSDB_MaximumPermissibleSpeed
    BeginMilepostPrefix,
    BeginMilepostSuffix,
    BeginMilepost,
    BeginTrackName,
    BeginLatitude,
    BeginLongitude,
    BeginElevation,
    EndMilepostPrefix,
    EndMilepostSuffix,
    EndMilepost,
    EndTrackName,
    EndLatitude,
    EndLongitude,
    EndElevation,
    Direction,
    Speed,
    TrainType,
    Description,
    InsertUser,
    S_ID
                                                     SELECT
      CASE WHEN @BegPrefix = 'null' THEN NULL
      ELSE @BegPrefix END,
                          CASE WHEN @BegSuffix = 'null' THEN NULL
      ELSE @BegSuffix END,
      @BeginMP ,
      @BeginTrackName  ,
      case WHEN @BegLat = 0 THEN NULL
      ELSE @BegLat END,
      CASE WHEN @BegLong=0 THEN NULL
      ELSE @BegLong END ,
      CASE WHEN @BegEle = 0 THEN NULL
      ELSE @BegEle END ,
      CASE WHEN @EndPrefix = 'null' THEN NULL
      ELSE @EndPrefix END,
                          CASE WHEN @EndSuffix = 'null' THEN NULL
      ELSE @EndSuffix END,
      @EnMP ,
      @EnTrackName  ,
      case WHEN @EndLat = 0 THEN NULL
      ELSE @EndLat END,
      CASE WHEN @EndLong=0 THEN NULL
      ELSE @EndLong END ,
      CASE WHEN @EndEle = 0 THEN NULL
      ELSE @EndEle END ,
      @Direction ,
      @Speed ,
      @TrainType ,
      CASE WHEN @Description ='null' THEN NULL
      ELSE @Description END ,
      @InsertUser ,
      @UID     
    INSERT INTO SSDB_MaxSpeed_History
                       MSID,
    BeginMilepostPrefix,
    BeginMilepostSuffix,
    BeginMilepost,
    BeginTrackName,
    BeginLatitude,
    BeginLongitude,
    BeginElevation,
    EndMilepostPrefix,
    EndMilepostSuffix,
    EndMilepost,
    EndTrackName,
    EndLatitude,
    EndLongitude,
    EndElevation,
    Direction,
    Speed,
    TrainType,
    Description,
    S_ID,
    NOTES ,
    [Action] ,
    InsertUser
                                 SELECT 
                          (Select MaximumPermissibleSpeedID from SSDB_MaximumpermissibleSpeed WHERE MaximumPermissibleSpeedID > @ID),
                          CASE WHEN @BegPrefix = 'null' THEN NULL
      ELSE @BegPrefix END,
                          CASE WHEN @BegSuffix = 'null' THEN NULL
      ELSE @BegSuffix END,
      @BeginMP ,
      @BeginTrackName  ,
      case WHEN @BegLat = 0 THEN NULL
      ELSE @BegLat END,
      CASE WHEN @BegLong=0 THEN NULL
      ELSE @BegLong END ,
      CASE WHEN @BegEle = 0 THEN NULL
      ELSE @BegEle END ,
      CASE WHEN @EndPrefix = 'null' THEN NULL
      ELSE @EndPrefix END,
                          CASE WHEN @EndSuffix = 'null' THEN NULL
      ELSE @EndSuffix END,
      @EnMP ,
      @EnTrackName  ,
      case WHEN @EndLat = 0 THEN NULL
      ELSE @EndLat END,
      CASE WHEN @EndLong=0 THEN NULL
      ELSE @EndLong END ,
      CASE WHEN @EndEle = 0 THEN NULL
      ELSE @EndEle END ,
      @Direction ,
      @Speed ,
      @TrainType ,
      CASE WHEN @Description ='null' THEN NULL
      ELSE @Description END ,
      @UID,
      NULL,
      'INSERT',
      @InsertUser 
    set @output='Success'
    --IF ((@COUNT >=1) AND (@COUNT =0))
    --BEGIN
    --  SET @output = 'ErrorLog'
    --END
    --IF (@COUNT = 0)
    -- BEGIN
    --SET @output ='Success'
    --END
    --END
    END
    END------------------------> 
    Deepa

    Hi Deepa,
    If I understand your question correctly, you would like the @Output parameter to contain the value "Success" only if all rows were successful. As soon as one row was found to be a duplicate, the value of @Output at the end of execution should be "ErrorLog".
    Currently, you modify the value of @Output in each iteration of the cursor, so at the end of execution you're left with the last value.
    In order to change that to work the way you want it, you need to set the value of @Output in the beginning of execution (before entering the cursor) to "Success", and as soon as there is a duplicate row, you should modify the value to "ErrorLog". This way,
    if all rows are successful, the value of @Output will be "Success" at the end of execution. On the other hand, if there is even a single duplicate row, the value of @Output will be "ErrorLog" at the end of execution.
    I hope this helps...
    Guy Glantser
    SQL Server Consultant & Instructor
    Madeira - SQL Server Services
    http://www.madeirasql.com

  • Where clause and order by to DAO classes

    Hi
    Is it ok(I mean design wise) to pass the 'where clause' conditions and order by clause as a parameter to the method of DAO class?

    Well, I would suggest you write seperate methods in your dao , one to select data without the where clause and one to select data with the where clause thrown in. If you have different 'where' clauses for selecting different kinds of data, have that many dao methods. The dao methods being specific know exactly what is the data that's coming in.
    Lets assume you have a list of purchase orders and each purchase order is indetified by a unique id called PURCHASE_ORDER_ID.
    1. The following code would populate a purchase order's details given an id.
    private statis final String QUERY_1 = "select * from PURCHASE_ORDERS where PURCHASE_ORDER_ID = ? ";
    PurchaseOrderModel getPurchaseOrderData(long poId){
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(QUERY_1);
         //set the poId passed as params to your query
         pst.setLong(1, poId);
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //populate data into a model          
         finally{
              //clean up resources
         return model;    
    }2. The following code would return a list of PurchaseOrderModel's whose shipping date falls between a set of dates selected by the user.
    private statis final String QUERY_2 = "select * from PURCHASE_ORDERS where SHIPPING_DATE between ? and ? ";
    PurchaseOrderModel getPurchaseOrdersBetweenDates(list bindValues){
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(QUERY_1);
         //set the dates passed as params to your query
         //we know that the List ought to contain only 2 dates
         pst.setDate(1, (Date)bindValues.get(0));
         pst.setDate(2, (Date)bindValues.get(1));
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //iterate and populate data into a model          
              //add model to a list
         finally{
              //clean up resources
         return list;    
         3. This is more interesting - the dao method searches a list of Purchase Orders starting with a set of specific words. The words themselves may be one or many. This means that the number of '?' in your prepared statement may be dynamic. Each element of the list is a String that contains the start substring of a purcahse order name. For example - the list may contain elements like ["a", "ab", "c", "gh"] and the dao method returns all purchase order starting with these names.
    private statis final String QUERY_3 = "select * from PURCHASE_ORDERS where ";
    PurchaseOrderModel getPurchaseOrderNameMatches(list bindValues){
         //construct the query dynamically
         StringBuffer query = new StringBuffer(QUERY_3);
         int count = 0;
         for(Iterator itr = bindValues.iterator(); itr.hasNext();;){
              String value = (String)itr.next();
              query.append ("name like 'value%' ");
              if (count != 0 and (count+1 != bindValues.length)){
                   query.append(" or ");
              count ++;          
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(query.toString());     
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //iterate and populate data into a model          
              //add model to a list
         finally{
              //clean up resources
         return list;    
    To sum up,
    1. You need as many methods as you have different kinds of searches (one method for each kind of 'where' clause).
    2. The ejb/business layer would examine the data and decide on which method to call.
    3. Increases coding effort, but makes the code clean and readable. Each layer does it's job. Thus we dont have ejbs forming 'where' clauses and so on.
    Having said that, it really is your decision - you should take into consideration the following factors -
    1. How big is the project ? If its a huge codebase developed by many people, then segregate the responsibilities clearly in each layer as I have outlined. For a small scale project, you could go with your approach.
    2. Whats the take on maintenance and future add-ons ? Do you see the codebase growing with time ?
    3. Is your project a commercial one - is it a product that needs to be maintained or is it a one-off development - develop once and you are done with it.
    4. What are the design considerations ? Is somebody going to audit code for quality ? Or is it a academic one ?
    You should take into account all these before deciding to go one way or the other.
    A general thumb rule should be that you should be convinced that your code readable (maintainable), scalable and efficient. Anything that you do towards these ends is good code/design despite what people/books/patterns say, IMO.
    cheers,
    ram.

  • Cast and Order by

    One of the requirements we have in generating reports is to order the results by 'users choice'.
    Example:
    The user wants a report for the following customer's, (in the order the user enters the customers name). The report is generated through a procedure using Utl_File, the GUI passes the list of customers as: 'BILL;ADAM;ZACHARY;OSCAR'
    The procedure parses the parameter into two variables, one the IN_LIST and the ORDER_LIST:
    IN_LIST = 'BILL','ADAM','ZACHARY','OSCAR'
    ORDER_LIST = 'BILL',1, 'ADAM',2, 'ZACHARY',3, 'OSCAR',4
    The statement is then parsed and opened with a ref cursor. The completed statement look (something) like:
    v_sql := 'Select * from My_Table where cust_name in ('
              || IN_LIST ||' ORDER BY DECODE( custname, '|| ORDER_LIST ||' ) ' ;Works great.
    But, I was wondering, is there any way of using, CAST with an Object Type that is a nested table type and a simple parse routine that returns this nested table type given a string input, to accomplish the same thing, keeping in mind the requirement of the ORDER BY.
    Something like:
    create or replace type myTableType as table of varchar2 (255);
    Create or replace function In_list
          ( p_string in varchar2 ) return myTableType  as
    l_string        long default p_string || ',';
    l_data          myTableType := myTableType();
    n               number;
    begin
      loop
         exit when l_string is null;
            n := instr( l_string, ',' );
            l_data.extend;
            l_data(l_data.count) :=  ltrim( rtrim( substr( l_string, 1, n-1 ) ) );
            l_string := substr( l_string, n+1 );
      end loop;
      return l_data;
    end;
    select ID, Cust_Name from Cust_Table
    where cust_name in
         (select * from
            TABLE(select cast( in_list('BILL,ADAM,ZACHARY,OSCAR') as mytableType)
                            from dual) )
    -- HOW TO USE AN ORDER BY ???

    Hello V Garcia
    Yes you can use objects to do what you want. This example just assumes the name and order strings match by order rather than repeating the names in both paramters. You could extend it to do that if you need, but it could get tricky if they switch the order of the names between the name and order by strings. You'd have to check for an existing row by name and be moving forwards and back the whole time. This assumption makes things quite a bit simpler.
    SQL> create or replace type sort_obj as object
      2      (str varchar2(255), n number)
      3  /
    Type created.
    SQL> create or replace type sort_tab as table of sort_obj
      2  /
    Type created.
    SQL> create or replace function sorttab
      2      (p_str in varchar2, p_n in varchar2, p_sep in varchar2)
      3  return sort_tab
      4  is
      5      l_str long := p_str || p_sep;
      6      l_n long := p_n || p_sep;
      7      l_sort_tab sort_tab := sort_tab();
      8  begin
      9      while l_str is not null loop
    10          l_sort_tab.extend(1);
    11          l_sort_tab(l_sort_tab.count) := sort_obj (
    12              rtrim(substr(l_str,1,instr(l_str,p_sep)),p_sep),
    13              to_number(rtrim(substr(l_n,1,instr(l_n,p_sep)),p_sep))
    14              );
    15          l_str := substr(l_str,instr(l_str,p_sep)+1);
    16          l_n := substr(l_n,instr(l_n,p_sep)+1);
    17      end loop;
    18      return l_sort_tab;
    19  end;
    20  /
    Function created.In 9i (at least in R2) then you can just do this.
    SQL> select * from
      2      table(sorttab('BILL,ADAM,ZACHARY,OSCAR','1,2,3,4',','))
      3      order by n;
    STR                 N
    BILL                1
    ADAM                2
    ZACHARY             3
    OSCAR               4
    SQL> select * from
      2      table(sorttab('BILL,ADAM,ZACHARY,OSCAR','3,2,4,1',','))
      3      order by n;
    STR                 N
    OSCAR               1
    ADAM                2
    BILL                3
    ZACHARY             4I only just found this because before that in 8i and up you need to cast to the table type
    SQL> select * from
      2      table(cast(sorttab('BILL,ADAM,ZACHARY,OSCAR','3,2,4,1',',') as sort_tab))
      3      order by n;
    STR                 N
    OSCAR               1
    ADAM                2
    BILL                3
    ZACHARY             4pre 8.1.x the full select from dual cast construct is needed.
    Its nice to see that life is getting easier.
    Hth
    Martin

  • EJB-QL and ORDER BY

    Hi all,
    this is my first post in this forum.
    I have a question:
    Is there a way in ejb-ql to make a query like this?
    SELECT a FROM Test a ORDER BY :field
    and then pass the parameter "field"?
    I need this because i want to implement pagination in my swing jtables.
    But when i need to sort data the only way that i've found is re-query with another order by param.
    If you want to suggest me another way to accomplish this, let me know!
    Very thanks, Eros.
    P.S.: I'm using Netbeans with Oracle Toplink Essentials
    Edited by: user6103941 on 13-ott-2008 15.16

    It is not possible to pass in a field name as a parameter. As an alternative you could specify the ordering using our native query/expression API.
    The following example was written using EclipseLink JPA:
            Query query = em.createQuery("SELECT e FROM Employee e");
            JpaHelper.getReadAllQuery(query).addAscendingOrdering("firstName");
            query.getResultList();This approach is basically casting down to the wrapped native query and populating the order-by directly.
    Doug

  • OPL8 (Order type dependent parameter)

    Hi All,
            Please clarify the following will be grateful.
    I have a inhouse material thatu2019s having alternative sequence. The above material uses order type PP01, so OPL8 (Order type dependent parameter) configured in such a way that ALTERNATIVE SEQUNCES is (Checked) and SEQUENCE EXCHANGE is u201C0u201D (i.e., No Selection).
    For the above settings what I meant is, even though if a material is having alternative sequences that wonu2019t get copied in to the order.
    But here is the issue starts for the following setting
    u2022     ALTERNATIVE SEQUNCES is (Checked) and
    u2022     SEQUENCE EXCHANGE is u201C0u201D (i.e., No Selection)
    Alternative sequence operations are available for the order on COOIS screen for the following selection
    LIST : Operations
    Layout: 000000000001 (Standard)
    Please explain me how ALTERNATIVE SEQUNCES and SEQUENCE EXCHANGE will work.
    Thanks in Advance

    Dear Madhan,
    Assign value 2 for sequence exchange and check the impact at the time of order creation.
    Check and revert back.
    Regards
    Mangalraj.S

  • Query by rownum and make substact

    Hello world ,
    i what query tow rows on same table and make substract between them
    for example
    Select rownum,sal from emp where rownum<=2;
    the result
    1 2000
    2 1000
    how to substract them from each other

    I will try to explain more
    for example i will fire this query
    select sal from emp where job='MANAGER' and rownum<=2 order by sal desc;
    the i got this result
    SAL
    10000
    9026
    i want to take
    first value and second
    substract them
    10000-9026
    i want to get the result of substaction.
    i neet it to use this on report

  • RowID , RowNum and Number Key???

    Dear Gurus
    I have a Little problem which I want to know for my personal knowledge and share with forum.
    I have recently developed small scale Inventory Management System using Form6i and Database 9.2. I have created three tables for cash sale e.g. CashMaster, Cashdetail and Cashdetdetail. Also for credit sale, three table
    CreditMaster, CreditDetail and Creditdetdetail and so on (lots of other tables, just for this problem I am considering two types of tables Cash and Credit).
    As the name suggested CashMaster is Master table, CashDetail is Detail table of CashMaster and CashDetDetail is again Detail table of CashMaster (One Master 2 Details Logic).
    I have used trigger at CashMaster block level to calculate and populate the Cash Bill No to three tables as follow
    (I didnot used sequence to generate CashBillNo as controling it a bit dificult and then you hae to put further check on Form success & saving it .... )
    Trigger Name:When New Block Instance
    Level: Block Level
    Item: CSBILLNO (CashMaster Bill No)
    select (nvl(max(csbillno), 0) + 1) into :cashmaster.csbillno from cashmaster;
    select (nvl(max(csbillno), 0) + 1) into :cashdetail.csbillno from cashmaster;
    select (nvl(max(csbillno), 0) + 1) into :cashdetdetail.csbillno from cashmaster;
    Compile and save it and there are no issues. Even while executing the form there is NO ISSUE (All Master Detail & Detail are taking input and saving it).
    But when I look into these tables in database using the cammand
    SQL> select rowid, rownum, csbillno from cashmaster;
    It generates following output
    ROWID ROWNUM CSBILLNO
    AAAHbhAABAAAMZCAAA 1 3
    AAAHbhAABAAAMZCAAB 2 1
    AAAHbhAABAAAMZCAAC 3 2
    AAAHbhAABAAAMZCAAD 4 4
    Similarly it is doing with CreditMaster. After 4 or 5 records it starts Aappending the records rightly at right place as shown above in record 4 (Rowid, RowNum and Record no should be equal or Something else ).
    I want to know why it is happening and what is the solution.
    Thanks in advance!!!
    Best Regards
    Thunder

    try the following
    create table p1 (id number, dscr varchar2(8));
    begin
    fo i in 1 .. 70000 loop
    insert into p1 (id, dscr) values (i,i);
    end loop;
    commit;
    end;
    try from a gui sql (such as sql developer, toad)
    select rowid, rownum, id, dscr;
    truncate p1;
    re populate the table using the above script
    chk again the data
    drop table p1;
    repeat
    i think you'll be suprised of what the db is doing...
    WE (developers-dba) have no control of where exactly the data are going to be stored in the tablespace/block/file
    the only way to be sure from forms and any other front end tool about the order
    of the the records that will be displayed to end user
    is to use explicitly the "order by" clause
    (or the order property of the block from builder)
    the order of that the forms will submit the insert stmnts depends where commit_form/commit is used
    if you use commit_form on a when-new-record-instance at the form level
    will commit each record after any navigation to a different record/block
    if you have on a form 2 unrelated blocks and you make
    insert into first block
    update into second block
    delete first block
    insert second block
    and then either the user presses commit or upon trigger exec
    forms will submit all the changes of one block
    and then all the changes of the other
    if you want a mechanism to ensure that data are displayed in the same order they are inserted in the db
    you have to use extra column to hold a sequence and/or timestamp

  • Rownum and last inserted row !!!!!!!!!!!!

    hi everybody,
    I am at present using oracle 8i Release 2. According to my knowledge and "Oracle 8 complete reference", when we use ROWNUM, the rownum is decided when the data is selected from the database. So when we use "order by" clause actually the rownum gets jumbled up.
    But to my surprise when i did something like this on my SQl prompt row num is acting very "innocent" :)
    <Code>
    1* select rownum, empno from emp
    SQL> /
    ROWNUM EMPNO
    1 7369
    2 7499
    3 7521
    4 7566
    5 7654
    6 7698
    7 7782
    8 7788
    9 7839
    10 7844
    11 7876
    12 7900
    13 7902
    14 7934
    15 1
    15 rows selected.
    SQL> select rownum, empno from emp order by empno;
    ROWNUM EMPNO
    1 1
    2 7369
    3 7499
    4 7521
    5 7566
    6 7654
    7 7698
    8 7782
    9 7788
    10 7839
    11 7844
    12 7876
    13 7900
    14 7902
    15 7934
    15 rows selected.
    </Code>
    As you can see rownum is ordered again .. m i missing something.
    B)
    Is it possible to get a row that was inserted last. Does oracle guarantee that data retrieval will be according to the time of inssertion !!
    Thanx in advance
    Chetan

    Rownum is decided afeter the complete execution of ur SQL statment (it includes ordey by, group by, where etc.).
    you can get the last inserted row using:
    select * from emp where rowid=
    (select max(rowid) from emp);
    Regards
    Riaz

Maybe you are looking for

  • Output could not be issued

    Hi, We are in process of upgrade.now we are in testing face.When we testing vy printing sales order doucments from VF03 trasaction we are getting error message 'Output Could not be issue',but when we are trying to see print preview it appears correct

  • How can I return to the previous ios version?

    Version 7 is a step backward for me. >The Calendar does an awful job displaying the All-Day Events. >I can't figure out how to get the previous search page showing web search and Wikipedia search. >Where is an easy to follow description of the change

  • IDVD ejects disk (doesn't burn) and reboots MBP

    I want to burn a QuickTime movie (slideshow created in Aperture) to dvd using iDVD. I choose "OneStep DVD from Movie", import the movie, iDVD requests insert a recordable DVD disc, waits for disc to become ready -- then kicks out the disk and reboots

  • Frequent error on feed posting - iTunes server problem?!

    Since last friday iTunes server has a frequent problem accepting feeds for review. I had the same experiences as mentioned before. All the messages in this board point to one thing: iTunes server - mainly error 5002 Can someone of Apples staff PLEASE

  • Can't open drafts, sent, trash, or delivered mailboxes.

    When I open mail, I can open and see new mail and send but when I try to access any of the other boxes (drafts, sent, or trash) I just get the spinning wheel and nothing happens. I have to force quit to close email as well. When I take the apple.mail