Assigning a query dynamically to a cursor based on IF ELSE condotion

hello guys,
we are facing a problem while creating a procedure.
The procedure has been recreated in ORACLE from SQL SERVER 2005.
the problem is that in SQL server we can assign a query dynamically to a cursor so that it will be called at execution time.But this is not the case in oracle, i.e in Oracle its not allowed to assign a query to a cursor dynamically(OR IS IT...!!!)
the code is
vr_SQL varchar2(400);
declare
   cursor ord_cur  ;  <-----cursor declaration
  begin
   If v_pIsScrutiny = 0 then   +<--------------second condition+
      vr_SQL:='Select NVL(ServiceID,0)  ServiceID,OrdQty,+<-------query assignment to a variable+
          NVL(DrugID,0) DrugID,NVL(ServiceAmount,0) Rate,OrdDtlID 
          from Orderdtl inner join ordermst on Orderdtl.OrdID = ordermst.OrdID 
          Where Orderdtl.OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid  
          and TO_CHAR(ordermst.OrdDate,''DD-MON-YYYY'') 
          Between TO_CHAR(vr_pActivationDate,''DD-MON-YYYY'') 
          and TO_CHAR(vr_pExpiryDate,''DD-MON-YYYY'') 
          ) And NVL(Orderdtl.Cancelled,0) = 0 And NVL(Orderdtl.PackageID,0) = 0 
          and NVL(Orderdtl.DrugID,0) = 0;';
    Else  +<--------------first condition+
        Update OrderDtl Set PackageID = 0 , AllocationID = 0 , ConsumptionID = 0 
        Where OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid)  
        And AllocationID = v_pHCPAllocationID; 
       vr_SQL:= 'Select NVL(ServiceID,0)  ServiceID, +<-------query assignment to a variable+
       OrdQty,NVL(DrugID,0)  DrugID,NVL(ServiceAmount,0)
        Rate,OrdDtlID 
       from Orderdtl inner join ordermst on Orderdtl.OrdID = ordermst.OrdID 
       Where Orderdtl.OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid  
       and TO_CHAR(ordermst.OrdDate,''DD-MON-YYYY'') 
       Between TO_CHAR(vr_pActivationDate,''DD-MON-YYYY'') 
       and TO_CHAR(vr_pExpiryDate,''DD-MON-YYYY'') 
       ) And NVL(Orderdtl.Cancelled,0) = 0 And NVL(Orderdtl.PackageID,0) = 0;'; 
    end if;
       ord_cur is vr_SQL; +<----------query assigned to a cursor variable+
    ord_rec ord_cur%ROWTYPE;
   if not ord_cur%ISOPEN then
        open ord_cur;
   end if;
    loop
    fetch ord_cur into ord_rec;
    exit when ord_cur%NOTFOUND;So currently we are stuck with this problem.
Any solution would be of great help..
thank you

841363 wrote:
hello guys,
we are facing a problem while creating a procedure.
The procedure has been recreated in ORACLE from SQL SERVER 2005.
the problem is that in SQL server we can assign a query dynamically to a cursor so that it will be called at execution time.But this is not the case in oracle, i.e in Oracle its not allowed to assign a query to a cursor dynamically(OR IS IT...!!!)The problem is that you are thinking in SQL Server terms and Oracle just isn't SQL Server.
You need to consider using ref cursors for such things (sys_refcursor) e.g.
SQL> CREATE OR REPLACE PACKAGE reftest IS
  2    PROCEDURE test(P_no in number, cur_o OUT sys_refcursor);
  3  end;
  4  /
Package created.
SQL>
SQL> CREATE OR REPLACE PACKAGE body reftest as
  2    PROCEDURE test(P_no in number, cur_o OUT sys_refcursor) as
  3      myexc exception;
  4    BEGIN
  5      if P_no = 1 then
  6        open cur_o for select empno, ename from emp;
  7      elsif p_no =2 then
  8        open cur_o for select deptno, dname from dept;
  9      else
10        RAISE myexc;
11      END IF;
12    exception
13      when myexc then
14        raise_application_error(20991,'input must be 1 or 2');
15    end ;
16  end reftest;
17  /
Package body created.
SQL> var x refcursor;
SQL> exec reftest.test(1,:x);
PL/SQL procedure successfully completed.
SQL> print x;
     EMPNO ENAME
      7369 SMITH
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7876 ADAMS
      7900 JAMES
      7902 FORD
      7934 MILLER
14 rows selected.
SQL> exec reftest.test(2,:x);
PL/SQL procedure successfully completed.
SQL> print x;
    DEPTNO DNAME
        10 ACCOUNTING
        20 RESEARCH
        30 SALES
        40 OPERATIONS
SQL>

Similar Messages

  • Sorting records dynamically in REF cursor, based upon a dynamic field

    Hi,
    I have a REF CURSOR built by using row type, table type and PIPELINE function. I have opened the ref cursor now. I would like to update a field called 'RANK' based upon 'RATIO' field in the REF CURSOR. i.e order the records in the ref cursor by RATIO field and then update the RANK as 1, 2, 3, 4, ....
    Aim: I want to update a field in the REF CURSOR based upon another numeric field.
    Please help me.
    OPEN sales FOR
    SELECT RANK, ratio
    FROM TABLE (fngetfundholdingsale (in_primarykey, in_flag));
    loop
    fetch sales into sale1;
    exit when sales%notfound;
    --I want to update sale1.rank based upon ratio
    end loop;
    Thanks
    Ashok

    Try to use NDS (Native Dynamic SQL):
    l_order := 'ratio';
    OPEN sales FOR
    'SELECT rank' ||
    '  FROM TABLE (fngetfundholdingsale (:in_primarykey, :in_flag))' ||
    ' ORDER BY ' || l_order
      USING in_primarykey, in_flag;Regards,
    Zlatko

  • Cannot create dynamic page with cursor based on linked table

    I get the following error when i try to create a dynamic portal page that uses a pl/sql cursor:
    ORA-06550: line 1, column 24:
    PL/SQL: ORA-00980: synonym translation is no longer valid
    ORA-06550: line 1, column 24:
    PL/SQL: SQL Statement ignored (WWV-11230)
    Failed to parse as REPORTS - DECLARE CURSOR C1 IS SELECT * FROM
    [email protected]; BEGIN FOR R1 IN C1 LOOP HTP.P(','||'<BR>');
    END LOOP; END; (WWV-08300)
    Dynamic page:
    <HTML>
    <HEAD>
    <TITLE>Example</TITLE>
    </HEAD>
    <BODY>
    <H2>Example of A Dynamic Page</H2>
    <ORACLE>
    declare
    cursor c1 is
    select * from [email protected];
    begin
    for r1 in c1 loop
    htp.p('hello<br>');
    end loop;
    end;
    </ORACLE>
    </BODY>
    </HTML>
    When i use the sql query from the cursor in the page below, i get no errors:
    <HTML>
    <HEAD>
    <TITLE>Example</TITLE>
    </HEAD>
    <BODY>
    <H2>Example of A Dynamic Page</H2>
    <ORACLE>select * from [email protected]</ORACLE>
    </BODY>
    </HTML>
    I tried a dynamic page with a cursor on session_roles and had no problems. I assume that there is an issue with the database link or the privileges. The queries seem to get executed under portal_public;
    Oracle Portal Version: 9.0.4.0.99

    I get the following error when i try to create a dynamic portal page that uses a pl/sql cursor:
    ORA-06550: line 1, column 24:
    PL/SQL: ORA-00980: synonym translation is no longer valid
    ORA-06550: line 1, column 24:
    PL/SQL: SQL Statement ignored (WWV-11230)
    Failed to parse as REPORTS - DECLARE CURSOR C1 IS SELECT * FROM
    [email protected]; BEGIN FOR R1 IN C1 LOOP HTP.P(','||'<BR>');
    END LOOP; END; (WWV-08300)
    Dynamic page:
    <HTML>
    <HEAD>
    <TITLE>Example</TITLE>
    </HEAD>
    <BODY>
    <H2>Example of A Dynamic Page</H2>
    <ORACLE>
    declare
    cursor c1 is
    select * from [email protected];
    begin
    for r1 in c1 loop
    htp.p('hello<br>');
    end loop;
    end;
    </ORACLE>
    </BODY>
    </HTML>
    When i use the sql query from the cursor in the page below, i get no errors:
    <HTML>
    <HEAD>
    <TITLE>Example</TITLE>
    </HEAD>
    <BODY>
    <H2>Example of A Dynamic Page</H2>
    <ORACLE>select * from [email protected]</ORACLE>
    </BODY>
    </HTML>
    I tried a dynamic page with a cursor on session_roles and had no problems. I assume that there is an issue with the database link or the privileges. The queries seem to get executed under portal_public;
    Oracle Portal Version: 9.0.4.0.99

  • Can you change the data model query dynamically based on its parent query

    Hi
    Question:
    I have a data model query q1 and q2 is the child of q1
    Say q1 returns 2 rows and and
    for the first row
    i want q2 to be select 1 from table1
    for the second row
    i want q2 to be select 1 from table2
    Basically i want to build the q2 dynamically
    for each row fetched in q1.
    Can this be done?
    If so where do i write the code to achieve this
    Thanx in advance.
    Suresh

    One simple (but not very realistic) example:
    1. DATABASE TABLES AND DATA
    CREATE TABLE dept_all (
    deptno NUMBER (2),
    dname VARCHAR2 (20),
    in_usa CHAR (1) DEFAULT 'Y')
    INSERT INTO dept_all VALUES (10, 'DEPT 10', 'Y');
    INSERT INTO dept_all VALUES (20, 'DEPT 20', 'N');
    INSERT INTO dept_all VALUES (30, 'DEPT 30', 'Y');
    CREATE TABLE emp_usa (
    empno NUMBER (4),
    ename VARCHAR2 (20),
    deptno NUMBER (2))
    INSERT INTO emp_usa VALUES (1001, 'EMP 1001', 10);
    INSERT INTO emp_usa VALUES (1002, 'EMP 1002', 10);
    INSERT INTO emp_usa VALUES (3001, 'EMP 3001', 30);
    INSERT INTO emp_usa VALUES (3002, 'EMP 3002', 30);
    CREATE TABLE emp_non_usa (
    empno NUMBER (4),
    ename VARCHAR2 (20),
    deptno NUMBER (2))
    INSERT INTO emp_non_usa VALUES (2001, 'EMP 2001', 20);
    INSERT INTO emp_non_usa VALUES (2002, 'EMP 2002', 20);
    2. DATABASE PACKAGE
    Note that Oracle Reports 3.0 / 6i needs 'static' ref cursor type for building Report Layout.
    So, in package specification we must have both ref cursor types, static for Report Layout
    and dynamic for ref cursor query.
    CREATE OR REPLACE PACKAGE example IS
    TYPE t_dept_static_rc IS REF CURSOR RETURN dept_all%ROWTYPE;
    TYPE t_dept_rc IS REF CURSOR;
    FUNCTION dept_query (p_where VARCHAR2) RETURN t_dept_rc;
    TYPE t_emp_rec IS RECORD (
    empno emp_usa.empno%TYPE,
    ename emp_usa.ename%TYPE);
    TYPE t_emp_static_rc IS REF CURSOR RETURN t_emp_rec;
    TYPE t_emp_rc IS REF CURSOR;
    FUNCTION emp_query (
    p_in_usa dept_all.in_usa%TYPE,
    p_deptno dept_all.deptno%TYPE)
    RETURN t_emp_rc;
    END;
    CREATE OR REPLACE PACKAGE BODY example IS
    FUNCTION dept_query (p_where VARCHAR2) RETURN t_dept_rc IS
    l_dept_rc t_dept_rc;
    BEGIN
    OPEN l_dept_rc FOR
    'SELECT * FROM dept_all WHERE ' || NVL (p_where, '1 = 1') || ' ORDER BY deptno';
    RETURN l_dept_rc;
    END;
    FUNCTION emp_query (
    p_in_usa dept_all.in_usa%TYPE,
    p_deptno dept_all.deptno%TYPE)
    RETURN t_emp_rc
    IS
    l_emp_rc t_emp_rc;
    l_table VARCHAR2 (30);
    BEGIN
    IF p_in_usa = 'Y' THEN
    l_table := 'emp_usa';
    ELSE
    l_table := 'emp_non_usa';
    END IF;
    OPEN l_emp_rc FOR
    'SELECT * FROM ' || l_table || ' WHERE deptno = :p_deptno ORDER BY empno'
    USING p_deptno;
    RETURN l_emp_rc;
    END;
    END;
    3. REPORT - QUERY FUNCTIONS AND DATA LINK
    FUNCTION q_dept RETURN example.t_dept_static_rc IS
    BEGIN
    -- "p_where" is a User Parameter
    RETURN example.dept_query (:p_where);
    END;
    FUNCTION q_emp RETURN example.t_emp_static_rc IS
    BEGIN
    -- "in_usa" and "deptno" are columns from Parent Group (G_DEPT)
    RETURN example.emp_query (:in_usa, :deptno);
    END;
    Of course, we must create Data Link between Parent Group (G_DEPT) and Child Query (Q_EMP).
    Regards
    Zlatko Sirotic

  • How to build a query dynamically....

    hi...i want to build a query dynamically. i don't want to build query by using string buffer. i want to create it directly by using sql query itself.
    my situation is like this....i have four drop down list in a page. The user can search the things based on one or two or three or four selected values.
    how to build a query for this kind of situation....pls let me know.
    Edited by: success_shiva6mca on Mar 3, 2008 12:39 PM

    there are two problems with building sql directly.
    1. it allows sql injection
    2.it allows XSS
    google them and you will understand if you dont already.
    I will recoment catching the values and using preparedStatements

  • How to change VO query dynamically

    Hi,
    Iam trying to change the VO query dynamically. My req. is I have 6 columns in a header page 3 columns(default single column) for sorting purpose and another 3 columns(default single column) for data querying purpose.
    al these are in one view so I have created one VO.
    Sorting Searching
    A A
    B B
    C C
    When I give any values in Sorting and hit submit button VO query should change dynamically.
    I have searched older post regarding this.
    My query is some thing like this
    SELECT * from cust_table where a = NVL(:1 ,a)
    UNION
    SELECT * from cust_table where a<> NVL(:1 ,a)
    order by a
    Iam trying to pas the below part dynamicaly in my AM method
    vo.setWherecaluse("where a = NVL(:1 ,a)
    UNION
    SELECT * from cust_table where a<> NVL(:1 ,a)
    order by a ")
    and trying to pass the params to that query. But it is not working.Giving error "Bind variable could not find"
    Can any one suggest how to solve the issue.
    Thanks,
    Mahesh

    Hello Ajay,
    THanks for your response.
    My vo query is select col1,col2,col3,col4,col5,col6 from cust_table;
    and and changing vo.setwhereclause dynamically based on different scenerios.
    in one scenerio i need my query to be some thing like
    SELECT col1,col2,col3,col4,col5,col6 from cust_table where a = NVL(:1 ,a)
    UNION
    SELECT col1,col2,col3,col4,col5,col6 from cust_table where a <> NVL(:1 ,a)
    order by a
    so can i concatenate my vo.setwhereclause like *"where a = NVL(:1 ,a) UNION SELECT col1,col2,col3,col4,col5,col6 from cust_table where a NVL(:2 ,a) order by a"*
    in the setwhereclause iam setting bind variables is this method correct? Hope it is clear pleaselet me know if it is not clear I will explain in detail.
    Thanks,

  • How to create dynamic ed flash charts based on user selected fields in Orac

    Hi all,
    Can any of the experts please tellme "how to create dynamic ed flash charts based on user selected fields in Oracle apex".
    Thanks
    Manish

    Hello,
    Lots of different ways to do this, I blogged about one way (using a Pipelined function) here -
    http://jes.blogs.shellprompt.net/2006/05/25/generic-charting-in-application-express/
    Other options include using a PL/SQL function returning the string to use as the dynamic query etc.
    Hope this helps,
    John.
    Blog: http://jes.blogs.shellprompt.net
    Work: http://www.apex-evangelists.com
    Author of Pro Application Express: http://tinyurl.com/3gu7cd
    REWARDS: Please remember to mark helpful or correct posts on the forum, not just for my answers but for everyone!

  • How to show the columns dynamically in OBIEE report based on the selection?

    Hi,
    I have a requirement where the columns should be dynamically shown in report based on what we select in propmt page.
    I'm creating a report in OBIEE where i want to give an option to the end user to select the columns whichever he wants to see in the report.
    For example I have the following columns in the report already:
    Customer Name,
    Customer Number,
    Bank Account,
    Address
    I want to give an option to the user to select 'Customer Mail ID' dynamically and see the column to be displyed in the report along with the existing columns.
    Through 'Column Selector' user can select a single column at a time, but if he want to select more than one column, how can we do this ?
    Please help me out in resolving this issue.
    Thanks,
    Chaithanya.

    Hi Chaithanya,
    there's not a straight solution for this. You can create different analysis containing different number of columns and then directing the user to this analysis using Action Links or you can also use View Selector to switch from one view (analysis) to the other. But it's not going to be very flexible nor dynamic.
    J.

  • Assigning a Numeric Value in a Cell Based on Text in Another Cell

    In advance, thanks for your assistance. I'm trying, in vain, to assign a numeric value in a cell based on text (from a dropdown menu) in another cell. For example, in cell A5 I have a dropdown list that includes the options "blue", "red", "white", and "gold." I want cell C15 to be 2 if A5="blue"; I want C15 to be 0 if A5="red"; I want C15 to be 2 if A5="white"; and, I want C15 to be 1 if A5="gold."

    Tippet,
    This is a job for LOOKUP.
    The expression for the Result cell is: =LOOKUP(A2, Lookup :: A1:A4, Lookup :: B1:B4)
    The aux. table contains the matches that you assign for the colors.
    Regards,
    Jerry

  • How to pass the feild names of a select query dynamically?

    Hi
    How can we pass the feilds names in select query dynamically?
    For example in my selection screen i wil be giving the table name, and feilds in that table.....
    those feilds should be taken in my select query...
    instead of
    PARAMETERS : tab_name TYPE ddobjname .
      SELECT *
        FROM (tab_name)
        INTO TABLE <newtab>
       UP TO 25 ROWS.
    parametrs : feild1 like-------
                     feild2----
    i need select feild1 feild2 feild3    FROM (tab_name)
        INTO TABLE <newtab>
       UP TO 25 ROWS.

    by the way, contrary to popular belief there is no performance problem when using
    SELECT * FROM dbtab INTO CORRESPONDING FIELDS OF TABLE itab WHERE ...
    as long as the structure of itab contains only the required fields.
    I ran some benchmarks against this and above construct is maybe 0.1% slower (Oracle 10g) than a
    SELECT f1 f2 f3 f4 ... FROM dbtab INTO TABLE itab WHERE ...
    but is saves you from maintaining a potentially very long field list in your code. So when you need additional fields later on, you just add them to the DDIC structure or type definition and that's it.
    Maybe something you want to factor in here.
    Cheers
    Thomas

  • How to assign a query retrived value to a user defined  object in a table

    how to assign a query retrived value to a user defined  object in a table

    Rajeshwar,
    If you use the "Search" feature in this forum, you should be able to find helpful links to similar questions.  You could also look at the RecordSet and DoQuery documentation in the SAP Business One SDK Help Center documentation to assist you with your question.
    HTH,
    Eddy

  • Change query dynamically in DB Adapter

    Hi,
    Please answer these questions.
    1. How to change query dynamically in DB Adapter?
    2. I have 2 db adapters, if i got error in 1 db adapter then how to rollback?
    Regards,
    kpr

    Hi,
    <div class="jive-quote">How to change query dynamically in DB Adapter?</div>
    Unfortunately there is no way to pass the query dynamically in DB Adapter. The reasoning behind that is that the DB adapter configuration wizard creates multiple assist files for each operation including the xsd which can not be created for any query dynamically.
    <div class="jive-quote">I have 2 db adapters, if i got error in 1 db adapter then how to rollback?</div>
    Either use XA datasources or throw a rollback fault in the catch block.
    Regards,
    Neeraj Sehgal

  • Avoid Distributed query in PL/SQL cursor code

    Hi,
    I have to avoid a distributed qry in my cursor code in PL/SQL.
    The query follows like this,
    cursor c1
    is
    select a.test,b.test1,a.test2
    from apple a,
    [email protected] b,
    bat c
    where a.listid = b.listid
    and a.list_name = c.list_name;
    Now i need to split the above cursor into two .
    (1)I need to query appl and bat which is from local database into one and
    (2)Have to do something for the value from [email protected] is stored in a temp. table or PL/SQL table.So that ,i can use the PL/SQL table or temp table in my join in cursor ,instead of having a distributed query.
    By doing so,will the performance hit badly ?
    [Note: Imagine this scenario is taking place in Oracle 11i Apps]
    Regards,
    Prasanna Natarajan,
    Oracle ERP Tech Team.

    [url http://groups.google.de/group/comp.databases.oracle.server/browse_frm/thread/df893cf9be9b2451/54f9cf0e937d7158?hl=de&tvc=1&q=%22Beautified%22+code+runs+slower#54f9cf0e937d7158]Recently somebody complained about slow performance after code was beatified in PL SQL Developer, after recompilation without flag "Add Debug Information" it run faster...
    (just a guess)
    Best regards
    Maxim

  • Show blank texts instead of key or 'not assigned' in query-result

    Hi,
    is there a way / workaround to
    1. suppress # / 'not assigned' in query results?
    or
    2. show blank texts (if maintained) instead of the key
        (when showing texts for a characteristic in a query all characteristics with blank texts - none or ' ' -
         will show the key instead of the blan text) ?
    Thanks,
    Christoph

    Hi Christoph,
    there have been several posts concerning this topic. As Saad told there is no direct way within SAP standard to reach this aim.
    Depending on the Front-End Tools you are using these posts may help:
    Not assigned and # in BEX 7.0 WAD
    how to set field to blank if the data is # or unassigned
    Brgds,
    Marcel

  • Which authorizations are required for assigning a query to a role?

    Hi everybody,
    we try to set up some roles for "reporting power users". These guys should be alble to define new queries using BEx (works fine) and also should be able to assign these new defined queries to a role, so other users can use these roles.
    The idea is simple, but we're searching for the right authorization object (or - as i suppose - set of authorization objects) that enables the user to assign a query to a role (using that "enter to a role" button in the open / save dialog).
    At the moment, the user can user that button, and the role, he should the query assigned to is shown. After selecting the role and clicking button "create" it take some seconds and a message "error when saving. entry has not been created" is shown.
    Obviously, there is a problem with writing the role (or adding the new information to that role).
    So, could anyone help me and provide me with a list of authorization objects that are required.
    Thanks in advance,
      Alfred

    S_RFC
    S_TCODE
    S_USER_GRP
    S_BDS_D
    S_OD_SEND
    S_RS_AUTH
    S_RS_BCS
    S_RS_COMP
    S_RS_COMP1
    S_RS_FOLD
    S_RS_ICUBE
    S_RS_MPRO
    The above mentioned authorization objects are enough to add in the role and required for the accessing a query.
    particularly, S_RS_COMP, S_RS_COMP1, S_RS_MPRO, S_RS_ICUBE are the most important auth objects which are directly getting involved in authorization of a query in a role.
    SO, you have to assign the respective info area, info cube and info providers names in these auth objects.
    The same scenario , i am using in my project to give access to the queries in all the areas for my end users.
    The values and access/authorizations restrictions is up to your project requirement.
    Hope this would help you.

Maybe you are looking for