Declare Cursor from variable

Hi,
on an APEX page I can create a cursor from an item like this:
cursor c is &P999_SQL_QUERY.;
and there are no problems.
Now I want to do the same in a procedure, but how could that be done?
I pass the sql-Statement as a VARCHAR2 variable to the procedure, but I do not know how I can do that. I am not familar with bind variables or something like that.
Can anyone help me please?
Thank you,
Tim

> on an APEX page I can create a cursor from an item like this:
cursor c is &P999_SQL_QUERY.;
and there are no problems.
Except for the very real and harsh danger of SQL injection. Pardon for being blunt, but code like that is bloody dangerous and IMO quite silly.
> Now I want to do the same in a procedure, but how could that be done?
You have created an anonymous PL/SQL block that are parsed and compiled at run-time (with APEX PL/SQL code doing the deed).
You can do the same thing manually in PL/SQL writing your own code to perform this deed.
It will however be equally dangerous and silly to do.

Similar Messages

  • Create a cursor from a PL/SQL variable or an external file

    Dear friends,
    is there a way for me to make Oracle Forms read a cursor from a PL/SQL variable, or an external file? Let's suppose we have the code below:
    DECLARE
    cursor c_values is select * from my_table;
    r_values c_values%ROWTYPE;
    BEGIN
    for r_values in c_values loop
    do_something;
    end loop;
    END;
    In the situation described above, could I create "select * from my_table" from a PL/SQL variable (it could be something like p_cursor = 'select * from my_table'), or an external file - for example, make my form read the contents of c:\my_select.sql , where we see the "select * from my table" text?
    My question comes because I need to export data from select instructions that were dinamically created inside the form - that is, via PL/SQL -, and I don't want to rewrite it, but I'll have to do it if I have no choice. Your help will be greatly appreciated.
    Best regards,
    Franklin
    Edited by: franklinbrasil on 12/03/2009 11:33
    Edited by: franklinbrasil on 12/03/2009 11:35

    Dear friends,
    I am using DBMS_SQL package, which solved my problem. Please let me explain it better, if it's not clear.
    I have some PL/SQL blocks inside my form, which creates SQL queries dinamically, and a dinamically created SQL is stored into a VARCHAR2 variable. These SQL queries are exported for use in Oracle Graphics, but since OG is not being developed by Oracle anymore then I am trying to find a substitute for it.
    So I thought about creating an option for the final user: he/she can choose exporting data into Microsoft Excel, and user does what he/she wants, creating a customized graphic. Exporting into Excel works finely, with no problems at all - I could find a routine by searching on the web.
    My goal was to use the same queries created above to export data dinamically to Microsoft Excel, and I absolutely don't want to rewrite all these dinamically created queries - one which works dinamically, other with no flexibility inside my form. Worse than it, I have many other dinamically created queries, and I obviously don't want to rewrite them all - any maintenance in this form would be terrible, with each SQL instruction written twice.
    Since all dinamically created SQL instructions are stored inside a VARCHAR2 variable, I thought about reusing the same SQL, as explained above - and here we have your suggestions about using a ref cursor, execute immediate, and so on. And (answering Andreas) query structure is always based on the same table, but its structure changes a lot, depending on what the final user chooses in a drop-down list (it's a list of graphics options, where final user chooses one option, and form must mount SQL dinamically, based on user's choice).
    By using your explanations, I could find DBMS_SQL solution here: http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adg09dyn.htm#26799
    . Please notice that I had to change DBMS_SQL.native into 1 for it to work in my form. I'll mark all your answers as helpful because I can use them both for database and form purposes.
    If my message was not clear enough, please tell me and I'll try to make it more clear.
    Best regards,
    Franklin

  • OCI8: returning cursors from stored procedures

    The short version of my question is:
    In OCI8, how do open a cursor from the database stored procedure, return it to my C++ program and fetch from it, given that in OCI8 cursors and cursor functions are becoming obsoleted?
    The long version of the same question is:
    I am converting my C++ code from the Oracle 7.3 OCI driver to the Oracle8 OCI driver. One thing I did very frequently in Oracle 7.3 OCI code is open a multi-row select cursor within a stored procedure and return that cursor to my program. In the program, I would then do the fetching with the returned cursor. This was very useful, as it allows me to change the queries in the stored procedure (for example, to append information to certain columns or make some data in all uppercase) without recompiling the application due to a changed SQL string.
    My 7.3 psuedocode is as follows:
    stored procedure def:
    TYPE refCurTyp IS REF CURSOR;
    FUNCTION LoadEmployeeData RETURN refCurTyp;
    stored procedure body:
    FUNCTION LoadEmployeeData RETURN refCurTyp IS
    aCur refCurTyp;
    BEGIN
    OPEN aCur FOR
    SELECT emp_id, emp_name
    FROM employee_table
    ORDER BY emp_name;
    return aCur;
    END;
    OCI code: // all functions are simplified, not actual parameter listing
    // declare main cursor variable #1 and return cursor variable #2
    Cda_Def m_CDAstmt, m_CDAfunction;
    // open both cursors
    oopen(m_CDAstmt, ...);
    oopen(m_CDAfunction, ...);
    // bind cursor variable to cursor #2
    oparse(&m_CDAstmt, "BEGIN :CUR := MYPACKAGE.LoadEmployeeData; END;");
    obindps(&m_CDAstmt, SQLT_CUR, ":CUR", &m_CDAfunction);
    // run cursor #1
    oexn(&m_CDAstmt);
    // bind variables from cursor #2, and fetch
    odefineps(&m_CDAfunction, 1, SQLT_INT, &m_iEmpId);
    odefineps(&m_CDAfunction, 2, SQLT_CHAR, &m_pEmpName);
    while (!ofen(&m_CDAfunction))
    // loop: do something with fetch
    // values placed in m_iEmpID and m_pEmpName
    This works perfectly, and has really helped to make my code more maintainable. Problem is, in Oracle 8 OCI both cursors and the cursor functions (such as oopen()) are becoming obsoleted. Now it uses statement and environment handles. I know I can still use Cda_Def and cursors--for a while--within OCI8, but I need to know the official up-to-date method of returning a cursor from the database and fetching within my C++ code. Any code fragment, or explanation of what I need to do in OCI8 would be appreciated (perhaps I need to bind to a statement handle instead? But the stored procedure still returns a cursor.)
    The Oracle8 OCI has a new SQLT_ type, SQLT_RSET, which the header file defines as "result set type". Unfortunately, it's almost completely undocumented in the official documentation. Am I supposed to use this instead of the obsolete SQLT_CUR?
    Thanks,
    Glen Mazza

    Email me diorectly and I will get you some code that might help. I fail to see the relevance of posting this type of information in the JDeveloper forum.

  • How to return a ref cursor from this dbms_sql?

    Hi,
    Can anyone show me how to return a ref cursor from this dbms_sql based procedure? I see 11g has a dbms_sql.to_refcursor(cursor_handle). How can this be done is 10g?
    Thx.
    CREATE OR REPLACE PROCEDURE Sample_Get_t
    p_sample_id sample.sample_id%TYPE,
    p_contract_id sample.contr_id%TYPE
    IS
    cursor_handle INT;
    sql_stmnt varchar2(500);
    rows_processed NUMBER;
    BEGIN
    sql_stmnt :=
    'SELECT
    sample_id,
    contr_id,
    rcpt_id
    FROM
    sample s
    WHERE
    s.contr_id = :1
    and s.sample_id = :2
    ORDER BY
    sample_id';
    cursor_handle := dbms_sql.open_cursor;
    dbms_sql.parse(cursor_handle, sql_stmnt, dbms_sql.native);
    dbms_sql.bind_variable(cursor_handle, ':1', p_contract_id);
    dbms_sql.bind_variable(cursor_handle, ':2', p_sample_id);
    rows_processed := dbms_sql.execute(cursor_handle);
    dbms_sql.close_cursor(cursor_handle);
    END Sample_Get_t;

    In 10 this cannot be done with dbms_sql (to my knowledge). There are a couple of other options.
    1) open the ref cursor for the dynamic statement using bind variables (or SYS_CONTEXT variables, which i prefer since they are much easier to deal with when you are dynamically adding predicates).
    declare
       wRefCursor  SYS_REFCURSOR;
    begin
       open wRefCursor for 'select * from all_objects where owner = :Logged_in_user' using user;
    end;
    /or using the context (the context will bind for you)
    declare
       wRefCursor  SYS_REFCURSOR;
    begin
       open wRefCursor for 'select * from all_objects where owner = SYS_CONTEXT(''CONTEXT_NAME'', ''VARIABLE_NAME'') ';
    end;
    /Be aware that contexts ALWAYS return varchar values, so if you are comparing to a number you should wrap it in TO_NUMBER, a date, TO_DATE and so on....
    2) change the DBMS_SQL to do an insert into a global temporary table and return the ref cursor which select's * from GTT;
    3) upgrade to Oracle 11 :)

  • How to declare cursor in procedure based on if condition?

    Hi Experts,
    In sql server I have eprocedure in which I declare cursor like this:
    IF (@int_cntCondition = 1 )
    BEGIN
    DECLARE Date_Cursor CURSOR FOR select HolidayCcy,HolidayDate from Definition..HolidayCalendar WITH (NOLOCK) where
    HolidayCcy in (@Deposit_Currency,@Alternate_Currency)
    AND CONVERT(SMALLDATETIME,CONVERT(VARCHAR(25),HolidayDate,106)) >=
    CONVERT(SMALLDATETIME,CONVERT(VARCHAR (25),@T_Date,106))
    END
    ELSE
    BEGIN
    DECLARE Date_Cursor CURSOR FOR select HolidayCcy,HolidayDate from Definition..HolidayCalendar WITH (NOLOCK) where
    HolidayCcy in (@Deposit_Currency,@Alternate_Currency,@Bank_Base_Currency)
    AND CONVERT(SMALLDATETIME,CONVERT(VARCHAR(25),HolidayDate,106)) >=
    CONVERT(SMALLDATETIME,CONVERT(VARCHAR(25),@T_Date,106))
    END
    I have to declare same cursor in oracle based on 'if' condition.
    But in oracle stored procedur cursor has to declare outside of Begin statment of procedure, so how can I declare This cursor in Orracle?
    if anyone know about it, Plese help or send any link to refer.
    Thanks.

    Digambar wrote:
    I have to declare same cursor in oracle based on 'if' condition.The simple answer is to use a reference cursor data type. E.g.
    SQL> create or replace procedure GetObjects( cur in out sys_refcursor, objType varchar2 ) is
      2  begin
      3          case
      4                  when upper(objType) = 'EMP' then
      5                          open cur for select * from emp;
      6 
      7                  when upper(objType) = 'DEPT' then
      8                          open cur for select * from dept;
      9 
    10          end case;
    11  end;
    12  /
    Procedure created.
    SQL>
    SQL>
    SQL> --// define a host refcursor variable in client
    SQL> --// (e.g. VB, .Net, Java, etc)
    SQL> var c refcursor
    SQL>
    SQL> --// make the stored proc call
    SQL> begin GetObjects( :c, 'EMP' ); end;
      2  /
    PL/SQL procedure successfully completed.
    SQL>
    SQL> --// process cur reference in client
    SQL> print c
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 1980/12/17 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 1981/02/20 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 1981/02/22 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 1981/04/02 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 1981/09/28 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 1981/05/01 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 1981/06/09 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 1987/04/19 00:00:00       3000                    20
          7839 KING       PRESIDENT            1981/11/17 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 1981/09/08 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 1987/05/23 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 1981/12/03 00:00:00        950                    30
          7902 FORD       ANALYST         7566 1981/12/03 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 1982/01/23 00:00:00       1300                    10
    14 rows selected.
    SQL>
    SQL>
    SQL> --// make the stored proc call
    SQL> begin GetObjects( :c, 'DEPT' ); end;
      2  /
    PL/SQL procedure successfully completed.
    SQL>
    SQL> --// process cur reference in client
    SQL> print c
        DEPTNO DNAME          LOC
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
    SQL>

  • Populate a REF CURSOR from regular cursor...

    Hi all,
    I apologize if the answer to this is somewhere...I've been looking on the web for sometime and can't find an answer to the following problem. I have a Significant Events database that contains network based issues and problems. As problems are detected on the network an SE is issued and published. As the SE records are updated, NEW records are entered into the table and "linked" back to the original. Each update results in a new row. Thus, an SE with two updates would have a total of 3 lines. When the SE gets closed (set the column CLOSED to SYSDATE), only the "original" SE is closed, any updates are left open...aka, the CLOSED column is left null.
    That said, I need a way to get the original and/or latest updated SE rows from the table. Thus, I am trying to use a PL/SQL package. The PL/SQL "must" return a REF CURSOR as the results are being passed to a client process.
    My initial approach was within a PL/SQL procedure, I have an SQL statement that returns the SE originals. Once in that cursor I need to do the following:
    - Attempt to fetch any linked SE rows.
    - if no rows then
    - add the original to the REF CURSOR.
    - else
    - find latest SE update
    - add latest SE update to REF CURSOR.
    - end if
    My Question is : How do I manually "add" a row to a REF CURSOR?
    If this is not possible, is there a way to populate a REF CURSOR from maybe another construct like:
    TYPE ian_se_record is RECORD (
    se_id number
    ,linked_se_id number
    ,submitted date
    ,updated date
    ,closed date
    ,segroup varchar2(150)
    ,incident_start_time varchar2(150)
    ,business_units_affected varchar2(150)
    ,officenum varchar2(1500)
    ,sedetails varchar2(4000)
    TYPE ian_se_table is table of ian_se_record index by binary_integer;
    With the above construct I could:
    - Fill ian_se_table with the process described above.
    - And finally select off ian_se_table into the REF CURSOR?
    Any help would be greatly appreciated,
    adym

    Hi michaels,
    I've put your solution in place, but can't seem to get it to run. The two types were moved out of the package and into real types as you said. Here's the function, for brevity, I've remove some of the less important code:
    function ian_se_fetch return sys_refcursor
    is
        p_csr_events            sys_refcursor;
        cursor csr_items is
            select
                 se_id
        ...removed for brevity...
        /* END : csr_items  */
        ian_se_row     ian_se_record;
        ian_se_tbl     ian_se_table;
        l_lng_index    number;
        l_lng_linked   number;
        l_lng_id       number;
    begin
         * OPEN : Open the main cursor of originals...
        for the_item in csr_items loop
             * CHECK : Check for any updates to the original...
            l_lng_linked := 0;
            select count(*)
            into l_lng_linked
            from sig_se_t src
            where src.linked_se_id = the_item.se_id;
            l_lng_id := 0;    /* reset the se-id    */
            /* SE original...no linked records yet.    */
            if ( l_lng_linked = 0 ) then
                l_lng_id := the_item.se_id;
            /* SE updates...one or more updates are present.    */
            else
                begin
                    select
                         se_id
                    into l_lng_id
                    from sig_se_t src
                    where src.linked_se_id = the_item.se_id
                      and rownum = 1
                    order by updated desc; /* latest update    */
                exception
                    when too_many_rows then
                        l_lng_id := the_item.se_id;
                    when others then
                        l_lng_id := 0;
                end;
            end if;
            if ( l_lng_id != 0 ) then
                select
                     se_id
                    ,linked_se_id
                    ,submitted
                    ,updated
                    ,closed
                    ,segroup
                    ,incident_start_time
                    ,business_units_affected
                    ,officenum || decode( nvl(impact,'1')
                                      ,'1',''
                                      ,decode(impact
                                          ,'NA', ''
                                          ,':' || impact
                                  )                           impact
                    ,sedetails
                into ian_se_row.se_id
                    ,ian_se_row.linked_se_id
                    ,ian_se_row.submitted
                    ,ian_se_row.updated
                    ,ian_se_row.closed
                    ,ian_se_row.segroup
                    ,ian_se_row.incident_start_time
                    ,ian_se_row.business_units_affected
                    ,ian_se_row.officenum
                    ,ian_se_row.sedetails
                from sig_se_t src
                where src.se_id = l_lng_id;
                l_lng_index := nvl(ian_se_tbl.last,0)+1;
                ian_se_tbl(l_lng_index).se_id                   := ian_se_row.se_id;
                ian_se_tbl(l_lng_index).linked_se_id            := ian_se_row.linked_se_id;
                ian_se_tbl(l_lng_index).submitted               := ian_se_row.submitted;
                ian_se_tbl(l_lng_index).updated                 := ian_se_row.updated;
                ian_se_tbl(l_lng_index).closed                  := ian_se_row.closed;
                ian_se_tbl(l_lng_index).segroup                 := ian_se_row.segroup;
                ian_se_tbl(l_lng_index).incident_start_time     := ian_se_row.incident_start_time;
                ian_se_tbl(l_lng_index).business_units_affected := ian_se_row.business_units_affected;
                ian_se_tbl(l_lng_index).officenum               := ian_se_row.officenum;
                ian_se_tbl(l_lng_index).sedetails               := ian_se_row.sedetails;
            end if;
        end loop;
         * REF CURSOR : Open the ref cursor on the dataset...
        if ( nvl(ian_se_tbl.last,0) = 0 ) then
            p_csr_events := null;
        else
            open p_csr_events for
            select *
            from table (cast ( ian_se_tbl as ian_se_table ));
        end if;
        return p_csr_events;
    end;Here's the test. I keep getting the same error ORA-06530:
    SQL> variable v refcursor;
    SQL> exec :v:=pkg_ian.ian_se_fetch;
    BEGIN :v:=pkg_ian.ian_se_fetch; END;
    ERROR at line 1:
    ORA-06530: Reference to uninitialized composite
    ORA-06512: at "N0002501.PKG_IAN", line 131
    ORA-06512: at line 1
    SQL> print v
    ERROR:
    ORA-24338: statement handle not executedOther things I tried:
    - The ian_se_fetch() function was a procedure using an in out parameter...same error.
    - Wrote a small anonymous block and tried to LOOP/FETCH. Same ORA-06530 error.
    P.S. Line 131 of pkg_ian is the SELECT ... INTO ian_se_row.se_id, ...
    Any help would be greatly appreciated,
    tia,
    adym
    Message was edited by:
    alink

  • How return parameter ref Cursor from procedure using dynamic SQL?

    I sorry, but i very need help.
    I using Oracle 8.0.6
    I need to return parameter of type ref Cursor from procedure.
    create or replace package PlanExp is
    type cursortype is ref cursor;
    procedure ShowPlan (cursorparam out
    cursortype.............);
    end PlanExp;
    create or replace package body PlanExp is
    procedure ShowPlan (cursorparam out cursortype,
    .............) Is
    sql_str varchar2(1000);
    sql_str_select varchar2(100);
    sql_str_from varchar2(100);
    sql_str_where varchar2(500);
    Return_Code integer;
    Num_Rows integer;
    cur_id_sel integer;
    tSum_Plan DBMS_SQL.NUMBER_TABLE;
    tSum_Plan_Ch DBMS_SQL.NUMBER_TABLE;
    tSum_Plan_Day DBMS_SQL.NUMBER_TABLE;
    begin
    /* calculating string variables ........... /*
    sql_str := 'select ' || sql_str_select ||
    'from ' || sql_str_from ||
    'where ' || sql_str_where ||
    'group by ' || sql_str_select;
    cur_id_sel := dbms_sql.open_cursor;
    dbms_sql.parse(cur_id_sel, sql_str, dbms_sql.native);
    dbms_sql.define_array(cur_id_sel, 1, tSum_Plan, 20, 1);
    dbms_sql.define_array(cur_id_sel, 2, tSum_Plan_Ch, 20, 1);
    dbms_sql.define_array(cur_id_sel, 3, tSum_Plan_Day, 20, 1);
    Return_Code := dbms_sql.execute(cur_id_sel);
    delete from TEMP_SHOWPLAN;
    Loop
    Num_Rows := dbms_sql.Fetch_Rows(cur_id_sel);
    dbms_sql.column_value(cur_id_sel, 1, tSum_Plan);
    dbms_sql.column_value(cur_id_sel, 2, tSum_Plan_Ch);
    dbms_sql.column_value(cur_id_sel, 3, tSum_Plan_Day);
    if Num_Rows = 0 then
    exit;
    end if;
    Exit When Num_Rows < 20;
    End Loop;
    dbms_sql.close_cursor(cur_id_sel);
    end;
    end PlanExp;
    How return cursor (cursorparam) from 3 dbms_sql.column_value-s ?

    I am using Oracle 8.1.7, so I don't know if this will work in
    8.0.6 or not:
    SQL> CREATE TABLE test
      2    (col1                    NUMBER,
      3     col2                    NUMBER,
      4     col3                    NUMBER)
      5  /
    Table created.
    SQL> INSERT INTO test
      2  VALUES (1,1,1)
      3  /
    1 row created.
    SQL> INSERT INTO test
      2  VALUES (2,2,2)
      3  /
    1 row created.
    SQL> INSERT INTO test
      2  VALUES (3,3,3)
      3  /
    1 row created.
    SQL> CREATE TABLE temp_showplan
      2    (tSum_Plan               NUMBER,
      3     tSum_Plan_Ch            NUMBER,
      4     tSum_Plan_Day           NUMBER)
      5  /
    Table created.
    SQL> EDIT planexp
    CREATE OR REPLACE PACKAGE PlanExp
    IS
      TYPE CursorType IS REF CURSOR;
      PROCEDURE ShowPlan
        (cursorparam    IN OUT CursorType,
         sql_str_select IN     VARCHAR2,
         sql_str_from   IN     VARCHAR2,
         sql_str_where  IN     VARCHAR2);
    END PlanExp;
    CREATE OR REPLACE PACKAGE BODY PlanExp
    IS
      PROCEDURE ShowPlan
        (cursorparam    IN OUT CursorType,
         sql_str_select IN     VARCHAR2,
         sql_str_from   IN     VARCHAR2,
         sql_str_where  IN     VARCHAR2)
      IS
        sql_str                VARCHAR2 (1000);
        cur_id_sel             INTEGER;
        return_code            INTEGER;
      BEGIN
        DELETE FROM temp_showplan;
        sql_str := 'INSERT INTO   temp_showplan '
               || ' SELECT '   || sql_str_select
               || ' FROM '     || sql_str_from
               || ' WHERE '    || sql_str_where;
        cur_id_sel := DBMS_SQL.OPEN_CURSOR;
        DBMS_SQL.PARSE (cur_id_sel, sql_str, DBMS_SQL.NATIVE);
        return_code := DBMS_SQL.EXECUTE (cur_id_sel);
        DBMS_SQL.CLOSE_CURSOR (cur_id_sel);
        OPEN cursorparam FOR SELECT * FROM temp_showplan;
      END ShowPlan;
    END PlanExp;
    SQL> START planexp
    Package created.
    Package body created.
    SQL> VARIABLE g_ref REFCURSOR
    SQL> EXEC PlanExp.ShowPlan (:g_ref, 'col1, col2,
    col3', 'test', ' 1 = 1 ')
    PL/SQL procedure successfully completed.
    SQL> PRINT g_ref
    TSUM_PLAN TSUM_PLAN_CH TSUM_PLAN_DAY
             1            1             1
             2            2             2
             3            3             3

  • How to out Dynamic ref cursor from Procedure to Forms

    Hi
    I am trying to out Dynamic ref cursor from Procedure to Forms, But I am unable to do so. however cursor return the value within procedure but I am failed to capture the same in Forms
    Pl advice suggestion if any, Here I am attaching full procedure for reference
    CREATE PACKAGE winepkg
    IS
    TYPE wine IS RECORD ( mynumber number);
    /* Define the REF CURSOR type. */
    TYPE wine_type IS REF CURSOR RETURN wine;
    END winepkg;
    CREATE procedure find_wine
    (col1_in in number,
    c1 out winepkg.wine_type) as
    vsql varchar2(1000);
    cur sys_refcursor;
    x number;
    BEGIN
    vsql:='select bo_id from bo_details where bo_details.bo_id = '||col1_in ;
    open cur for vsql;
    c1:=cur;
    --fetch c1 into x;
    --dbms_output.put_line(x);
    END find_wine;
    In front end forms
    Declare
    TYPE F is REF CURSOR;
    CUR_F F;
    rec number;
    Begin
    break;
    find_wine( 1601480000011078,cur_f ) ;
    Loop
    fetch cur_f into rec ;
    Message(rec ) ;pause;
    exit when cur_f%notfound ;
    End loop ;
    exception
    when others then
    Message(sqlerrm) ;pause;
    End ;

    yo can use
    declare
    c_cursor EXEC_SQL.CursType;
    v_stmt varchar2(2000) = 'select a, b, c from mytab where cond1'; -- you can create this value dynamically
    begin
    c_cursor := Exec_SQL.Open_cursor;
    EXEC_SQL.PARSE(c_articulos, v_stmt);
    EXEC_SQL.DEFINE_COLUMN(c_articulos,1, v_colchar1, 30);
    EXEC_SQL.DEFINE_COLUMN(c_articulos,2, v_colchar2, 15);
    EXEC_SQL.DEFINE_COLUMN(c_articulos,3, v_colchar3, 30);
    v_exec := EXEC_SQL.EXECUTE(c_cursor);
    WHILE EXEC_SQL.FETCH_ROWS(c_cursor) > 0 LOOP
    EXEC_SQL.COLUMN_VALUE(c_cursor,1,v_colchar1);
    EXEC_SQL.COLUMN_VALUE(c_c_cursor,2,v_colchar2);
    EXEC_SQL.COLUMN_VALUE(c_c_cursor,3,v_colchar3);
    assign_values_to_block;
    END LOOP;
    EXEC_SQL.CLOSE_CURSOR(c_cursor);
    end;
    and WORKS IN FORMS 6

  • Query in SQL 2008R2 error Msg 1087, Level 15, State 2, Line 31 Must declare the table variable

    Hello Experts, 
    Can You help me; I get the follwing error in my query
    Msg 1087, Level 15, State 2, Line 31
    Must declare the table variable "@ASE_SUBART_GROEP".
    the @ASE_SUBART_GROEP is a self-defined table in this SQL environment.
    Maybe you know the error or the missing part
    Thanks in advance, Jos Dielemans

    I'm not familiar with SAP Business One unfortunately, so can only be of limited help here. But I'm going to guess that @ASE_SUBART_GROEP is a table variable passed to a stored procedure and is defined and passed down by the application, so you won't
    be able to copy-paste this code directly into management studio and get it to work.
    You could remove the join to return *all* records. Although the dataset might be very big
    SELECT T0.CardCode AS 'Klantnr'
    ,T0.CardName AS 'Klantnaam'
    ,T4.GroupName AS 'Klantgroep'
    ,T9.Descr AS 'Merknaam'
    ,T5.SlpName AS 'Verkoper'
    ,T3.MailCity AS 'Leverplaats'
    ,T7.NAME AS 'Leverland'
    ,T3.City AS 'Factuurplaats'
    ,T7.NAME AS 'Factuurland'
    ,T0.DocNum AS 'Documentnr'
    ,T0.DocDate AS 'Datum'
    ,Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) AS 'Jaar'
    ,RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2) AS 'Maand'
    ,(Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) + '-' + RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2)) AS 'Periode'
    ,T1.ItemCode AS 'Artikelnr'
    ,T2.ItemName AS 'Artikelnaam'
    ,T1.Quantity AS 'Aantal VEH'
    ,T2.SVolume AS 'Aantal EH per VEH'
    ,(T1.Quantity * T2.SVolume) AS 'Aantal EH'
    ,T8.UnitName AS 'EH-Naam'
    ,T6.ItmsGrpNam AS 'Artikelgroep'
    ,T2.U_ItemGrp AS 'Hoofdgroep'
    ,T10.NAME AS 'Subgroep'
    ,T1.CogsAcct AS 'Kostpr.rek.'
    ,T1.AcctCode AS 'Opbrengstrek.'
    ,T1.LineTotal AS 'BrutoOmzet'
    ,T0.DiscPrcnt AS 'Korting'
    ,(+ T1.LineTotal * (100 - T0.DiscPrcnt) / 100) AS 'NettoOmzet'
    FROM dbo.OINV T0
    INNER JOIN dbo.INV1 T1 ON T0.DocEntry = T1.DocEntry
    INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
    INNER JOIN OCRD T3 ON T0.CardCode = T3.CardCode
    INNER JOIN OCRG T4 ON T3.GroupCode = T4.Groupcode
    INNER JOIN OSLP T5 ON T3.SlpCode = T5.SlpCode
    INNER JOIN OITB T6 ON T2.ItmsGrpCod = T6.ItmsGrpCod
    INNER JOIN OCRY T7 ON T3.Country = T7.Code
    LEFT OUTER JOIN OLGT T8 ON T2.SVolUnit = T8.UnitCode
    LEFT OUTER JOIN UFD1 T9 ON T3.U_ZPgroep = T9.FldValue
    AND TableID = 'OCRD'
    AND FieldID = 2
    --LEFT OUTER JOIN @ASE_SUBART_GROEP T10 ON T2.U_ASE_SUB_ARTGROEP = T10.Code
    WHERE T0.DocDate >= '20120101'
    AND T0.Canceled = 'N'
    UNION ALL
    SELECT T0.CardCode AS 'Klantnr'
    ,T0.CardName AS 'Klantnaam'
    ,T4.GroupName AS 'Klantgroep'
    ,T9.Descr AS 'Merknaam'
    ,T5.SlpName AS 'Verkoper'
    ,T3.MailCity AS 'Leverplaats'
    ,T7.NAME AS 'Leverland'
    ,T3.City AS 'Factuurplaats'
    ,T7.NAME AS 'Factuurland'
    ,T0.DocNum AS 'Documentnr'
    ,T0.DocDate AS 'Datum'
    ,Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) AS 'Jaar'
    ,RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2) AS 'Maand'
    ,(Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) + '-' + RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2)) AS 'Periode'
    ,T1.ItemCode AS 'Artikelnr'
    ,T2.ItemName AS 'Artikelnaam'
    ,- T1.Quantity AS 'Aantal VEH'
    ,T2.SVolume AS 'Aantal EH per VEH'
    ,(- T1.Quantity * T2.SVolume) AS 'aantal EH'
    ,T8.UnitName AS 'EH-Naam'
    ,T6.ItmsGrpNam AS 'Artikelgroep'
    ,T2.U_ItemGrp AS 'Hoofdgroep'
    ,T10.NAME AS 'Subgroep'
    ,T1.CogsAcct AS 'Kostpr.rek.'
    ,T1.AcctCode AS 'Opbrengstrek.'
    ,- T1.LineTotal AS 'BrutoOmzet'
    ,T0.DiscPrcnt AS 'Korting'
    ,(+ T1.LineTotal * (100 - T0.DiscPrcnt) / 100) AS 'NettoOmzet'
    FROM dbo.ORIN T0
    INNER JOIN dbo.RIN1 T1 ON T0.DocEntry = T1.DocEntry
    INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
    INNER JOIN OCRD T3 ON T0.CardCode = T3.CardCode
    INNER JOIN OCRG T4 ON T3.GroupCode = T4.Groupcode
    INNER JOIN OSLP T5 ON T3.SlpCode = T5.SlpCode
    INNER JOIN OITB T6 ON T2.ItmsGrpCod = T6.ItmsGrpCod
    INNER JOIN OCRY T7 ON T3.Country = T7.Code
    LEFT OUTER JOIN OLGT T8 ON T2.SVolUnit = T8.UnitCode
    LEFT OUTER JOIN UFD1 T9 ON T3.U_ZPgroep = T9.FldValue
    AND TableID = 'OCRD'
    AND FieldID = 2
    --LEFT OUTER JOIN @ASE_SUBART_GROEP T10 ON T2.U_ASE_SUB_ARTGROEP = T10.Code
    WHERE T0.DocDate >= '20120101'
    AND T0.Canceled = 'N'
    ORDER BY T0.CardCode
    The join to the table variable has been commented out above, so the code should run. After that you might want to update the WHERE clause to include only particular sub-groups

  • Ref cursor from anonymous block

    I have no problem to get a ref cursor from a Fill method call with an anonymous pl/sql block. But if my anonymous block contains a DECLARE section, the dataset is not populated.
    ex:
    BEGIN OPEN :cuInscription FOR SELECT column FROM table; END;
    is ok but with
    DECLARE A NUMBER; BEGIN OPEN :cuInscription FOR SELECT column FROM table; END;
    the dataset is not populated (even if the SQL CALL succeed).
    Do you know about that?

    This issue has been fixed in the ODP.NET 92040 release.

  • Getting "Must declare the scalar variable" Error

    Hello All,
    I have write following query to block invoice which has Prices not equal to PriceList as below.
    -- To Block Invoices which has Prices not equal to PriceList
    IF (@transaction_type='A' OR @transaction_type = 'U') AND CAST(@OBJECT_TYPE = '18')
    BEGIN
        SELECT T1.ItemCode,
                T1.Price AS PO_Price,
                T2.U_ListPrice AS Listed_Price
            FROM OPCH AS T0 
            INNER JOIN
            PCH1 AS T1 ON
            T0.DocEntry = T1.DocEntry
            LEFT OUTER JOIN    
            [dbo].[@PRICELISTS] AS T2 ON
            T1.ItemCode = T2.U_ItemNo
        WHERE
                    T1.DocEntry = @list_of_cols_val_tab_del) AND
            (T1.Price <> T2.U_ListPrice)   
    BEGIN
    SET @error = 123
    SET @error_message = 'Deviation in price'
    END
    END
    But after Execution got following Errors
    Msg 137, Level 15, State 2, Line 2
    Must declare the scalar variable "@transaction_type".
    Msg 137, Level 15, State 2, Line 19
    Must declare the scalar variable "@list_of_cols_val_tab_del".
    Msg 137, Level 15, State 1, Line 22
    Must declare the scalar variable "@error".
    Msg 137, Level 15, State 1, Line 23
    Must declare the scalar variable "@error_message".
    Please Help
    Regards
    Hitul

    Hi Hitul,
    Please check Snapshot.
    Please see Red Lines for SBO_SP_TransactionNotification Procedure.
    Paste your code below ADD YOUR CODE HERE.
    Hope this help
    Regards::::
    Atul Chakraborty

  • Must declare the Scalar variable *@prompt*.. (IES 10901)".

    Hi,
    I am getting an error: "Database error Must declare the Scalar variable *@prompt*.. (IES 10901)".
    backend: SQLServer
    The dim, Lovs are valid in IDT universe.
    There is a Fiscal Year Month Dim in Universe=SELECT
      cast(convert(varchar(6),DATEADD (YEAR,"COST_SUMMARY_FACT_VR"."FISC_YEAR"-1900,DATEADD(MONTH,"COST_SUMMARY_FACT_VR"."FISC_PERIOD"-1,DATEADD(DAY,0,0 ))),112) as int)
    FROM "COST_SUMMARY_FACT_VR"
    Lov
    There are two LOVs FP_From, FP_To
    1) FP_From= select distinct cast(convert(varchar(6),DATEADD (YEAR,"COST_SUMMARY_FACT_VR"."FISC_YEAR"-1900,DATEADD(MONTH,"COST_SUMMARY_FACT_VR"."FISC_PERIOD"-1,DATEADD(DAY,0,0 ))),112) as int) from COST_SUMMARY_FACT_VR order by 1
    2) FP_To=select distinct cast(convert(varchar(6),DATEADD (YEAR,"COST_SUMMARY_FACT_VR"."FISC_YEAR"-1900,DATEADD(MONTH,"COST_SUMMARY_FACT_VR"."FISC_PERIOD"-1,DATEADD(DAY,0,0 ))),112) as int) from COST_SUMMARY_FACT_VR order by 1
    Prompts
    There are two universe prompts
    1) FP_From is Numeric and LOV FP_From is attached
    2) FP_To is Numeric and LOV FP_To is attached
    Using the universe prompts in webi as
    Fiscal Year Month between FP_From and FP_To
    Qry is executing perfectly in backend.

    In addition to Visakh's solution: the reason you got the error message is because the piece of dynamic SQL is not part of the stored procedure, but constiutes a scope of its own. Thus variables declared in the surrounding procedure are not visible.
    Also, you should the dynamic SQL this way:
    SET @sql = N'
    SELECT @Result=COUNT( Id ) FROM  ' + quotename(@TableName) +
    ' WHERE RunRegisterKey=@ID'
    SET @Params = N'@Result int OUTPUT, @ID int'
    EXEC sys.sp_executesql @sql,@Params,@Result = @Result OUT, @ID = @ID
    That is, use quotename for the table name, in case you have a table named
    sys.objects; SHUTDOWN WITH NOWAIT; --
    Furthermore, pass @ID as a parameter rather than concatenating it to the string. It is both easier and safer.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Must declare the scalar variable

    I Am getting error as Must declare the scalar variable "@Imageid" for the following code,while executing,
    exec spGetPager  ' ' , ' ', ' 3 ', ' '
    In my coding I pass querystring value like 1,2,3 etc
    CREATE PROCEDURE spGetPager
          @PageNo int = 1,  
          @ItemsPerPage int = 1,  
     @Imageid int,
          @TotalRows int out  
    AS  
    BEGIN  
      SET NOCOUNT ON  
      DECLARE  
        @StartIdx int,  
        @SQL nvarchar(max),   
        @SQL_Conditions nvarchar(max),   
        @EndIdx int
          IF @PageNo < 1 SET @PageNo = 1  
          IF @ItemsPerPage < 1 SET @ItemsPerPage = 10  
          SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1  
          SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1  
          SET @SQL = 'SELECT Imageid,Imagepath,imagename,username  
                    FROM (  
                    SELECT  ROW_NUMBER() OVER(ORDER BY Imageid) AS Row, *  
                          FROM  Imageupload ) AS tbl WHERE Imageid=@Imageid AND Row >= '  
                                        + CONVERT(varchar(9), @StartIdx) + ' AND  
                           Row <=  ' + CONVERT(varchar(9), @EndIdx)  
          EXEC sp_executesql @SQL  
          SET @SQL = 'SELECT @TotalRows=COUNT(*) FROM Imageupload'  
          EXEC sp_executesql  
            @query = @SQL,  
            @params = N'@TotalRows INT OUTPUT',  
            @TotalRows = @TotalRows OUTPUT  
    END
    Thanks in Advance

    you cant use variable directly in concatenation operator as its of type int. you need to cast it first as below
    CREATE PROCEDURE spGetPager
    @PageNo int = 1,
    @ItemsPerPage int = 1,
    @Imageid int,
    @TotalRows int out
    AS
    BEGIN
    SET NOCOUNT ON
    DECLARE
    @StartIdx int,
    @SQL nvarchar(max),
    @SQL_Conditions nvarchar(max),
    @EndIdx int
    IF @PageNo < 1 SET @PageNo = 1
    IF @ItemsPerPage < 1 SET @ItemsPerPage = 10
    SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1
    SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1
    SET @SQL = 'SELECT Imageid,Imagepath,imagename,username
    FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY Imageid) AS Row, *
    FROM Imageupload ) AS tbl WHERE Imageid=' + CAST(@Imageid AS varchar(50)) + ' AND Row >= '
    + CONVERT(varchar(9), @StartIdx) + ' AND
    Row <= ' + CONVERT(varchar(9), @EndIdx)
    EXEC sp_executesql @SQL
    SET @SQL = 'SELECT @TotalRows=COUNT(*) FROM Imageupload'
    EXEC sp_executesql
    @query = @SQL,
    @params = N'@TotalRows INT OUTPUT',
    @TotalRows = @TotalRows OUTPUT
    END
    That being I didnt understand why you need dynamic sql here. There's no dynamicity involved as i see
     you could simply use a sql like below
    CREATE PROCEDURE spGetPager
    @PageNo int = 1,
    @ItemsPerPage int = 1,
    @Imageid int,
    @TotalRows int out
    AS
    BEGIN
    SET NOCOUNT ON
    DECLARE
    @StartIdx int,
    @EndIdx int
    IF @PageNo < 1 SET @PageNo = 1
    IF @ItemsPerPage < 1 SET @ItemsPerPage = 10
    SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1
    SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1
    SELECT Imageid,Imagepath,imagename,username
    FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY Imageid) AS Row, *
    FROM Imageupload ) AS tbl WHERE Imageid=@Imageid
    AND Row >= @StartIdx
    AND Row <= @EndIdx
    SELECT @TotalRows=COUNT(*) FROM Imageupload
    END
    to achieve same requirement.
    Make sure you read
    http://www.sommarskog.se/dynamic_sql.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Must declare the scalar variable error

    I am getting the error "Must declare the scalar variable "@Result""  when i execute the below query
    declare @sql nvarchar(max),
    @tablename varchar(200),
    @Id int,
    @Result int
    set @tablename='xyz'
    set @id=1
    SET @sql = '
    SELECT @Result=COUNT( Id ) FROM  ' + @TableName+ ' WHERE RunRegisterKey=' +convert(nvarchar(100),@ID)  
    EXEC sys.sp_executesql @sql

    In addition to Visakh's solution: the reason you got the error message is because the piece of dynamic SQL is not part of the stored procedure, but constiutes a scope of its own. Thus variables declared in the surrounding procedure are not visible.
    Also, you should the dynamic SQL this way:
    SET @sql = N'
    SELECT @Result=COUNT( Id ) FROM  ' + quotename(@TableName) +
    ' WHERE RunRegisterKey=@ID'
    SET @Params = N'@Result int OUTPUT, @ID int'
    EXEC sys.sp_executesql @sql,@Params,@Result = @Result OUT, @ID = @ID
    That is, use quotename for the table name, in case you have a table named
    sys.objects; SHUTDOWN WITH NOWAIT; --
    Furthermore, pass @ID as a parameter rather than concatenating it to the string. It is both easier and safer.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Can we define cursors from in procedure while using .procedure file?

    Hi Team,
    Can we define cursors from in procedure while using .procedure file?
    I have a catalog procedure in which am using cursors and it is working fine. But while trying to create the same procedure using .procedure , the validation is failing with "An error occurred while parsing your procedure".
    Request your suggestions.
    Regards,
    Krishna Tangudu

    Hi Krishna,
    I also tried to find the validation for procedure and failed. What was on my mind when I posted earlier was related to Window -> Properties -> SAP HANA -> Modeler -> Validation Rules but this is not the same for procedure.
    Also the validation error seems to not being raised by Studio but the server, so it's not a frontend validation anyway.
    Trying to replicate your error I create two procedures here and both worked fine with cursor.
    The behavior you found was the same I found, the .procedure goes to repository and _SYS_BIC after activation and .hdbprocedure goes to catalog only.
    As far as I understood as you are moving from catalog (manually) and it worked on catalog (.hdbprocedure), I could check the declaration of table types of header as it's the main difference.
    Despite this investigation of declaration, you can try create it on modeler direct and see what you found on .procedure created. This can speed up investigation.
    Regards, Fernando Da Rós
    BTW: I'm faced an very strange behavior that each caracter I type on .procedure or .hdbprocedure freezes studio by around 15 seconds ?!?!?!?! (studio rev73)

Maybe you are looking for

  • Functional Module:Need  some sample source code.

    Hi All, I have created  a customized table   u2018ZStock_Order_Dealeru2019 with the following fields: Stock_Order_Dealer Dealer Number S2D order Number      Line item Number      Material Number      Ordered Quantity      Batch Number      Received Q

  • How can I increase hard drive space on my mac book pro

    I have only about 30 gb left on my hard drive. I have a mac book pro I bought in 2013. I've deleted or transferred to an external hard drive as much material as possible. How can I find out what is taking up all the room?? My dropbox always says it c

  • Please help me about Workflow

    sir/mam,i am new for workflow,will any one give me guidence for how i will start with workflow ..please help me about this topic....?

  • How to create Role in Workflow

    Hi, In Oracle documentation setting global workflow preferences, the Workflow Administrator should be set to A responsibility, not to A user. My questions are: 1. How can I create A responsibility? Is it using A PL/SQL API?Or using insert statement?

  • Purchasing Group problem

    Hi all, we have implemented SRM 4.0 with CCM 2.0 in extended classic scenario. Therefor we have created 3 local purchasing groups. My question is which setting controls which purchasing group is chosen by creating a shopping cart? BR, Bernd