Need to execute a anonymous block

Hi guys,
I have one proc like below.
proc_expl(
empid in number,
ename in varchar2,
marks in marks_typ);
marks_type is record type which consists of 3 subjects.
marks_typ(sub1 number, sub2 number, sub3 number)
and i declared with table type this record type.
now I want to execute anonymous block and i am giving parameter values like below:
declare
empid in number,
ename in varchar2,
marks in marks_typ
begin
empid := 123,
ename := 'abc',
marks marks_typ := marks_typ(55,67,78);
proc_expl(
empid => empid,
ename => ename,
marks => marks_typ);
end;
can any one please suggest me why this is not executing properly.
thanks in advance!
Rgds,
LKR

Try the below
CREATE OR REPLACE TYPE marks_type IS OBJECT (sub1 NUMBER(10),
                                             sub2 NUMBER(10),
                                             sub3 NUMBER(10)
CREATE OR REPLACE TYPE marks_typ IS TABLE OF marks_type;
CREATE OR REPLACE PROCEDURE proc_expl(empid NUMBER,
                                      ename VARCHAR2,
                                      marks marks_typ
AS
v_marks marks_typ:= marks;
BEGIN
FOR i IN 1..v_marks.COUNT
  LOOP
   DBMS_OUTPUT.PUT_LINE(v_marks(i).sub1||','||v_marks(i).sub2||','||v_marks(i).sub3);
  END LOOP;
END;
SET SERVEROUTPUT ON
DECLARE
empid NUMBER;
ename VARCHAR2(20);
marks marks_typ := marks_typ();
BEGIN
empid := 123;
ename := 'abc';
marks.extend;
marks(1) := marks_type(55,67,78);
proc_expl(empid,ename,marks);
END;
Execution:-
SQL> DECLARE
  2  empid NUMBER;
  3  ename VARCHAR2(20);
  4  marks marks_typ := marks_typ();
  5  BEGIN
  6  empid := 123;
  7  ename := 'abc';
  8  marks.extend;
  9  marks(1) := marks_type(55,67,78);
10  proc_expl(empid,ename,marks);
11  END;
12  /
55,67,78
PL/SQL procedure successfully completed.
Hope it helps

Similar Messages

  • How to execute a anonymous block

    hi all,
    I want to execute a anonymous pl/sql block using dbms_sql.
    Is it possible to use through dbms_sql. suppose i am having a 100 lines of code in an anonymous block will i be able to execute it through dbms_sql or plz tell me any other way to do it.
    note: i will have this anonymous block code in a table. i should take the block from the table and execute it.
    Please help me how to do it.
    thanks
    hari

    > we have a table driven approach for our project.
    That does not make sense as a table driven approach implies a data driven approach.
    Which means that the code is static/fixed and processes the data.
    It is very complex to dynamically generate code to perform actions, instead of generating data to tell the code what actions to perform.
    This is usually only done in the domains of artificial intelligence and experts systems - and one can debate just how effective that approach is...
    Which raises the question as why you would choose such an approach in the first place?
    Do you also realise that this dynamic code will likely trash the SQL Shared Pool due to a lack of bind variables? And trashing the Shared Pool that way is the #1 reason for poor performing applications using Oracle?

  • Getting value with an anonymous block using ODP

    Hi all!
    I have a problem I hope someone can help me with. I believe it to be a minor one. I am trying to imbed an anonymous block into my .net app and use it dynamically to get a value from the database depending on the values in a tables. Since my procedure is quite large I am displaying a small example proc for simplicity purposes. Basically I want to execute an anonymous block from my app that will return a value (not a row or rows) from the database. The code is below:
    Private Sub test()
    Dim cn As New OracleConnection(profileString)
    Try
    Dim sb As New System.Text.StringBuilder
    sb.Append("Declare ")
    sb.Append("v_maxnum varchar2(6); ")
    sb.Append("Begin ")
    sb.Append("Select max(to_number(email_address_id)) into ")
    sb.Append("v_maxnum from CVWH14_CDRV_TEST.EMAIL_ADDRESS_TBL; ")
    sb.Append("dbms_output.put_line(v_maxnum); ")
    sb.Append("Exception ")
    sb.Append("When Others ")
    sb.Append("Then ")
    sb.Append("dbms_output.put_line('Program run errors have occurred.'); ")
    sb.Append("End; ")
    Dim cmd As New OracleCommand(sb.ToString, cn)
    With cmd
    cmd.CommandType = CommandType.Text
    Dim parm As New OracleParameter
    parm.ParameterName = "v_maxnum"
    parm.OracleType = OracleType.VarChar
    parm.Direction = ParameterDirection.Output
    parm.Size = 6
    cmd.Connection.Open()
    Dim ret As Object = cmd.ExecuteScalar()
    Dim res As String = cmd.Parameters.Item(0).Value.ToString -- **Error is occuring here**
    cmd.Connection.Close()
    cmd.Dispose()
    End With
    Catch ex As Exception
    MessageBox.Show(ex.Message, "Error")
    'End If
    If cn.State = ConnectionState.Open Then
    cn.Close()
    End If
    End Try
    End Sub
    The exception error reads "Invalid Index 0 for this OracleParameterCollection with Count=0."
    If I can figure out how to get a parameter value from the database via the anonymous block, I can apply the logic to the real application. Any help or direction I could receive would be greatly appreciated. Thanks for reading this post!

    Thank you for responding. The code that I posted was just one of many ways I have tried. I retried the proc making just 2 changes:
    Private Sub test()
    Dim cn As New OracleConnection(profileString)
    Try
    Dim sb As New System.Text.StringBuilder
    sb.Append("Declare ")
    sb.Append("v_maxnum varchar2(6); ")
    sb.Append("Begin ")
    sb.Append("Select max(to_number(email_address_id)) into ")
    sb.Append("v_maxnum from CVWH14_CDRV_TEST.EMAIL_ADDRESS_TBL; ")
    sb.Append("dbms_output.put_line(:v_maxnum); ") -- !Changed this to a bind variable!
    sb.Append("Exception ")
    sb.Append("When Others ")
    sb.Append("Then ")
    sb.Append("dbms_output.put_line('Program run errors have occurred.'); ")
    sb.Append("End; ")
    Dim cmd As New OracleCommand(sb.ToString, cn)
    With cmd
    cmd.CommandType = CommandType.Text
    Dim parm As New OracleParameter
    parm.ParameterName = ":v_maxnum" -- !Changed this to a bind variable!
    parm.OracleType = OracleType.VarChar
    parm.Direction = ParameterDirection.Output
    parm.Size = 6
    cmd.Connection.Open()
    Dim ret As Object = cmd.ExecuteScalar() -- !The error is now occuring here!
    Dim res As String = cmd.Parameters.Item(0).Value.ToString
    cmd.Connection.Close()
    cmd.Dispose()
    End With
    Catch ex As Exception
    MessageBox.Show(ex.Message, "Error")
    If cn.State = ConnectionState.Open Then
    cn.Close()
    End If
    End Try
    End Sub
    I am now getting the error message "Not all variables bound". Any more help or direction that you could throw my way would be greatly appreciated.

  • Basic anonymous block which drops and creates a table

    Version: 11.2.0.3
    I am fairly new to PL/SQL.
    We have a table named CHK_CNFG_DTL.
    I want to create a backup table for CHK_CNFG_DTL which will be named like CHK_CNFG_DTL_BKP_<timestamp> eg: CHK_CNFG_DTL_BKP_JULY_22_2013
    Creation of this backup table has to be automated so, I want to create an anonymous block which will first drop the existing backup table and then create a new backup table from the original table.
    The below code works fine. But the very first time when you run it , the loop won't iterate because there is no such table named CHK_CNFG_DTL_BKP%.
    declare
    v_stmt varchar2(1000);
    v_date date;
    begin
      for rec in
      (select * from user_tables where table_name like 'CHK_CNFG_DTL_BKP%' )
        loop
            begin
                execute immediate 'alter session set nls_date_format=''DD_MON_YYYY''';
                v_stmt := 'drop table '||rec.table_name|| ' purge';
                dbms_output.put_line(v_stmt);   ----- Drops Old backup table
                execute immediate v_stmt;
                select sysdate into v_date from dual;
                v_stmt := 'create table CHK_CNFG_DTL_BKP_'||to_date(v_date)||' as select * from CHK_CNFG_DTL';
                dbms_output.put_line('Creating Bkp table CHK_CNFG_DTL_BKP_'|| to_date(v_date) );
                dbms_output.put_line(v_stmt);
                execute immediate v_stmt;  --- Creates new Backup table
            exception
            when others
            then
            dbms_output.PUT_LINE (rec.table_name||'-'||sqlerrm);
            end;
        end loop;
    end;
    PL/SQL procedure successfully completed.
    -- Backup table not created.
    SQL> select table_name from user_Tables where table_name like 'CHK_CNFG_DTL%';
    TABLE_NAME
    CHK_CNFG_DTL
    Of course, this can fixed by creating a table like bleow before executing the anonymous block
    SQL> create table CHK_CNFG_DTL_BKP_JULY_22_2013 (x varchar2(37));
    Table created.
    and now the block will succesfully run like
    24  end;
    25  /
    drop table CHK_CNFG_DTL_BKP_JULY_22_2013 purge
    Creating Bkp table CHK_CNFG_DTL_BKP_22_JUL_2013
    create table CHK_CNFG_DTL_BKP_22_JUL_2013 as select * from CHK_CNFG_DTL
    PL/SQL procedure successfully completed.
    But this is going to production . We can't a table like CHK_CNFG_DTL_BKP_JULY_22_2013 without a proper business reason.
    How can I modify the above code so that if even if there is no such table like 'CHK_CNFG_DTL_BKP%' , it will proceed to create the backup table?

    Hi,
    Why won't you push the creation of the backup out of the loop ?
    declare
    v_stmt varchar2(1000);
    v_date date;
    begin
      for rec in
      (select * from user_tables where table_name like 'CHK_CNFG_DTL_BKP%' )
        loop
            begin
                execute immediate 'alter session set nls_date_format=''DD_MON_YYYY''';
                v_stmt := 'drop table '||rec.table_name|| ' purge';
                dbms_output.put_line(v_stmt);   ----- Drops Old backup table
                execute immediate v_stmt;
            exception
            when others
            then
            dbms_output.PUT_LINE (rec.table_name||'-'||sqlerrm);
            end;
        end loop;
                select sysdate into v_date from dual;
                v_stmt := 'create table CHK_CNFG_DTL_BKP_'||to_date(v_date)||' as select * from CHK_CNFG_DTL';
                dbms_output.put_line('Creating Bkp table CHK_CNFG_DTL_BKP_'|| to_date(v_date) );
                dbms_output.put_line(v_stmt);
                execute immediate v_stmt;  --- Creates new Backup table
    end;

  • PL/SQL Anonymous Block - Trying to Call Function within Cursor

    Hello -
    I need to create an anonymous block that contains a cursor and a function. I want to call the function from within the cursor, and the function will basically take an ID as its IN parameter, and will return a comma separated list of values.
    However, when I try to do this I get the error " function 'GET_PAYMENT_DATES' may not be used in SQL".
    Does anyone know of a workaround? I'm trying to avoid having to store this function.
    Thanks,
    Christine

    Exploring Keith's suggestion of using the function code inline in your SQL:
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> drop table t;
    Table dropped.
    test@ORA10G> drop table monetary_trans;
    Table dropped.
    test@ORA10G>
    test@ORA10G> create table monetary_trans as
      2  select 1 household_id, trunc(sysdate)-10 received_date from dual union all
      3  select 1, trunc(sysdate)-9 from dual union all
      4  select 1, trunc(sysdate)-8 from dual union all
      5  select 2, trunc(sysdate)-7 from dual union all
      6  select 2, trunc(sysdate)-6 from dual;
    Table created.
    test@ORA10G>
    test@ORA10G> create table t as
      2  select rownum x, rownum*10 y from dual connect by level <= 4;
    Table created.
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> select * from monetary_trans;
    HOUSEHOLD_ID RECEIVED_
               1 28-DEC-08
               1 29-DEC-08
               1 30-DEC-08
               2 31-DEC-08
               2 01-JAN-09
    test@ORA10G> select * from t;
             X          Y
             1         10
             2         20
             3         30
             4         40
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> -- the function code could be rewritten as follows
    test@ORA10G> --
    test@ORA10G> select household_id,
      2         ltrim(sys_connect_by_path(rd,','),',') payment_dates
      3    from
      4  (
      5  select household_id,
      6         to_char(received_date,'mm/dd/yy') as rd,
      7         row_number() over (partition by household_id order by 1) rn,
      8         count(*) over (partition by household_id) cnt
      9    from monetary_trans
    10    -- and the constraints here in the where clause
    11  )
    12  where level = cnt
    13  start with rn = 1
    14  connect by prior household_id = household_id
    15  and prior rn = rn - 1
    16  and household_id = 1 -- <== this is the input parameter value
    17  ;
    HOUSEHOLD_ID PAYMENT_DATES
               1 12/28/08,12/29/08,12/30/08
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> -- and can be used as an inline view when joined with other tables
    test@ORA10G> --
    test@ORA10G> select t.y,
      2         fn.payment_dates
      3    from t,
      4         (select household_id,
      5                 ltrim(sys_connect_by_path(rd,','),',') payment_dates
      6          from (select household_id,
      7                       to_char(received_date,'mm/dd/yy') as rd,
      8                       row_number() over (partition by household_id order by 1) rn,
      9                       count(*) over (partition by household_id) cnt
    10                  from monetary_trans)
    11          where level = cnt
    12          start with rn = 1
    13          connect by prior household_id = household_id
    14          and prior rn = rn - 1
    15         ) fn
    16   where t.x = fn.household_id
    17  ;
             Y PAYMENT_DATES
            10 12/28/08,12/29/08,12/30/08
            20 12/31/08,01/01/09
    test@ORA10G>
    test@ORA10G>HTH
    isotope

  • Need an anonymous block for fake update,

    I have a table called sk_a
    create table sk_a (a number, b date, c varchar2(10));
    and an audit table
    create sk_a_audit (audit_id number, a number, b date, c varchar2(10),dml_action varchar2(4));
    and sequence sk_a_audit_seq
    create sequence sk_a_audit_seq
    when any insert or update happens into sk_a table, respective data should insert into sk_a_audit table
    and trigger is
    CREATE OR REPLACE TRIGGER SK_A_TRG
    AFTER INSERT OR UPDATE
    ON SK_A
    FOR EACH ROW
    DECLARE
    l_code NUMBER;
    l_errm VARCHAR2 (64);
    BEGIN
    IF (INSERTING OR UPDATING)
    THEN
    INSERT INTO SK_A_audit
    VALUES (sk_a_audit_seq.NEXTVAL, :NEW.a,
    :NEW.B, :NEW.C ,'I');
    END IF;
    EXCEPTION
    WHEN OTHERS
    THEN
    l_code := SQLCODE;
    l_errm := SUBSTR (SQLERRM, 1, 64);
    DBMS_OUTPUT.put_line ('DML Operation is failed ' || l_code || l_errm);
    END;
    sk_a may or maynot have primary or unique keys,
    now my requirement is
    audit table will be deleted by business users,,
    and then I have to run an update on sk_a table (fake update) so that data will come and insert into audit table,,,,
    so that audit table will be back with all the data of sk_a table again,
    I need an anonymous block for this, can any one help on this,

    audit table will be deleted by business users,,
    and then I have to run an update on sk_a table (fake update) so that data will come and insert into audit table,,,,
    so that audit table will be back with all the data of sk_a table again,
    I need an anonymous block for this, can any one help on this,Y? audit table was deleted by busineess users..? could u pls explain it..?
    if u know that users going to delete the audit table, then take the back of the table. that is better instead of fake update.
    U can use exp utility for taking that back up
    Pls reply
    S

  • WHEN-TREE-NODE-SELECTED need 2 Execute-Query on Master-Detail data block

    I optimize tree using this link
    http://andreas.weiden.orcl.over-blog.de/article-29307730.html_+
    For huge amount of data (Accountings)
    All i need for now is
    WHEN-TREE-NODE-SELECTED need 2 Execute-Query on the data block
    DECLARE
    htree ITEM;
    node_value VARCHAR2(100);
    BEGIN
    IF :SYSTEM.TRIGGER_NODE_SELECTED = 'TRUE' THEN
    -- Find the tree itself.
    htree := FIND_ITEM ('BL_TREE.IT_TREE');
    node_value := FTREE.GET_TREE_NODE_PROPERTY( htree, :SYSTEM.TRIGGER_NODE ,  ftree.node_value  );
       GO_BLOCK ('GL_ACCOUNTS');
       set_block_property('GL_ACCOUNTS', DEFAULT_WHERE , 'ACCOUNT_ID ='|| node_value  );
    EXECUTE_QUERY;
    END IF;
    END;The above code is working fine 4 the detail block which is *'GL_ACCOUNTS'*
    when i substitute is Master block which is 'GL_ACCOUNTS_TYPES' it doesn't display all data
    Help is Appriciated pls.
    Regards,
    Abdetu...

    Hello
    In WHEN-TREE-NODE-SELECTED i modified the following code :_
    DECLARE
            htree ITEM;
           node_value VARCHAR2(100);
           parent_node FTREE.NODE;
    BEGIN
      IF :SYSTEM.TRIGGER_NODE_SELECTED = 'TRUE' THEN
      -- Find the tree itself.
      htree := FIND_ITEM ('BL_TREE.IT_TREE');
      -- Get the parent of the node clicked on. 
                  parent_node := FTREE.GET_TREE_NODE_PARENT ( htree, :SYSTEM.TRIGGER_NODE );
           GO_BLOCK('GL_TYPES');
                set_block_property('GL_TYPES', DEFAULT_WHERE , 'TYPE_ID ='|| parent_node  );
                  EXECUTE_QUERY;
      -- Get the detail of the parent node
          node_value := FTREE.GET_TREE_NODE_PROPERTY( htree, :SYSTEM.TRIGGER_NODE ,  ftree.node_value  );
               GO_BLOCK('GL_ACCOUNTS');
               set_block_property('GL_ACCOUNTS', DEFAULT_WHERE , 'ACCOUNT_ID ='|| node_value  );     
                   EXECUTE_QUERY;
          END IF;
    END;
    FRM-40350 : Query caused no records to be retrieved but i have records in the data base ...!
    Well, Do u think that's because in ur package i retrieve only the detail block ?
    Regards,
    Abdetu...

  • Need help displaying item based on pl/sql anonymous block

    This is probably something really simple but I'm stuck.....
    On purchase order, I want to show related parent project name and ID. What is the best way to do it? I have created a region based on pl/sql anonymous block, and that works, but the data is above where I want it. I want the project name and ID to show up in the region w/ all the other fields.
    I have created an item in the region that has other form fields, item is based on pl/sql anonymous block, w/ same code as above region, and the item doesn't find the data. What's the difference? Is it because the item doesn't save state? In order to choose for the item to be based on pl/sql anon block, APEX made me choose Display as Text (based on PLSQL, does not save state).
    Please see this picture:
    http://farm3.static.flickr.com/2391/2658673285_04f157a3fa_o.png
    thanks!
    ~Darby

    this is weird.. Now it is working. I didn't change anything! What the heck?
    http://farm3.static.flickr.com/2010/2659557520_73e54b67ea_o.png

  • Reference value of an SQLPLUS variable in a PL/SQL anonymous block

    All,
    Is there a way of referencing an SQLPLUS variable within a PL/SQL anonymous block. See my example below........
    sqlplus -s /@${L_DB_SID} <<-ENDOFSQL >> ${L_LOGFILE}
    SET FEEDBACK OFF
    SET PAGES 0
    SET SERVEROUTPUT ON
    WHENEVER SQLERROR EXIT SQL.SQLCODE
    WHENEVER OSERROR EXIT 2
    VARIABLE l_ret_sts NUMBER;
    VARIABLE l_ret_msg VARCHAR2(300);
    exec sh_plsql_owner.sh\$secure_batch.p\$set_role(p_ret_sts => :l_ret_sts);
    begin
    if :l_ret_sts > 0 then
    dbms_output.put_line('l_ret_sts:'||:l_ret_sts||':SECURITY');
    else
    ${L_PLSQL_PROG}(p_ret_type => 0, p_ret_sts => :l_ret_sts, p_ret_msg => :l_ret_msg);
    dbms_output.put_line('l_ret_sts:'||NVL(:l_ret_sts,0));
    dbms_output.put_line('l_ret_msg:'||:l_ret_msg);
    end if;
    end;
    exit
    ENDOFSQL
    I need to be able to reference :l_ret_sts in the begin block using the if statement "if :l_ret_sts > 0 then"
    :l_ret_sts is populated in a procedure call beforehand.
    However it seems as though the begin block cannot reference the value returned to :l_ret_sts.
    Any ideas.
    Ian.

    Managed to solve this. I put my call to the package that the role enables via dynamic sql....
    sqlplus -s /@${L_DB_SID} <<-ENDOFSQL >> ${L_LOGFILE}
    SET FEEDBACK OFF
    SET PAGES 0
    SET SERVEROUTPUT ON
    WHENEVER SQLERROR EXIT SQL.SQLCODE
    WHENEVER OSERROR EXIT 2
    VARIABLE l_ret_sts NUMBER;
    VARIABLE l_ret_msg VARCHAR2(300);
    exec dbms_application_info.set_client_info('CONTROL-M');
    exec sh_plsql_owner.sh\$secure_batch.p\$set_role(p_ret_sts => :l_ret_sts);
    declare
    v_text varchar2(500);
    begin
    if :l_ret_sts > 0 then
    dbms_output.put_line('l_ret_sts:'||:l_ret_sts||':SECURITY');
    else
    v_text := 'begin ${L_PLSQL_PROG}(p_ret_type => 0, p_ret_sts => :1, p_ret_msg => :2);end;';
    execute immediate v_text using in out :l_ret_sts, in out :l_ret_msg;
    dbms_output.put_line('l_ret_sts:'||NVL(:l_ret_sts,0));
    dbms_output.put_line('l_ret_msg:'||:l_ret_msg);
    end if;
    end;
    exit
    ENDOFSQL
    Cheers
    Ian.

  • Calling a function which has a CLOB parameter via an anonymous block.

    OK,
    we are moving a lot of exports currently done by Crystal to just be done by stored procs.
    So we have a load of existing, some extremely length SQL statements used for these exports.
    IN the exports, we have meaningful column headings, so we have a 'lookup' file where all the column names are listed with the desired column name text listed against it.
    So - to make our lives easier(i thought) , I have written a Oracle function to extract al;l of the column names as a list (see below).
    It works fine except for when I am trying to pass in a SQL treatment that is longer than 4000 character.
    What I want to be able to do is simply have an anonymous block that callls my function, I will be running this via SQL explorer.
    Something like......
    DECLARE
    theSQL CLOB;
    BEGFIN
    theSQL := 'SELECT * FROM ORDERS WHERE 1=0';
    SELECT GET_COLUNS_AS_LIST( theSQL, 0 ) FROM DUAL;
    END;
    However, when I run this I get the error................
    PLS-00428: an INTO clause is expected in this SELECT statement
    06550. 00000 - "line %s, column %s:\n%s"
    *Cause:    Usually a PL/SQL compilation error.
    If I hard code the SQL like this, SELECT GET_COLUNS_AS_LIST( 'SELECT * FROM ORDERS WHERE 1=0', 0 ) FROM DUAL; all is well.
    Also, I am going to need to be able to pass in SQL ststement longer that 4000 characters as weel so please bear that in mind.
    I am not an Oracle guy, so I guess I am missing something fundamental - Please enlighten me with regards to this.
    Any help extremely appreciated.
    CREATE OR REPLACE FUNCTION GET_COLUNS_AS_LIST( P_SQL IN VARCHAR2, Add_Equals_Sign Number := 0)
    RETURN CLOB
    IS
    fResult VARCHAR2(32000);
    HNDL NUMBER;
    d NUMBER;
    colCount INTEGER;
    i INTEGER;
    rec_tab DBMS_SQL.DESC_TAB;
    cCRLF VARCHAR(2) := CHR(13) || CHR(10);
    LONG_SQL dbms_sql.varchar2s;
    n INTEGER;
    l INTEGER;
    u INTEGER;
    StartPos INTEGER;
    BEGIN
    --INITIIALISE RESULT
    fResult := '';
    HNDL := DBMS_SQL.OPEN_CURSOR;
    l := Length( P_SQL );
    u := ( l / 1000 ) + 1;
    FOR n IN 1..u
    LOOP
    StartPos := ( n - 1 ) + 1;
    LONG_SQL( n ) := SubStr( P_SQL, StartPos, 1000 );
    END LOOP;
    if HNDL <> 0 THEN
    DBMS_SQL.PARSE ( c => HNDL,
    statement => LONG_SQL,
    lb => 1,
    ub => u,
    lfflg => false,
    language_flag => DBMS_SQL.NATIVE );
    --DBMS_SQL.PARSE( HNDL, P_SQL, DBMS_SQL.NATIVE);
    d := DBMS_SQL.EXECUTE( HNDL );
    DBMS_SQL.DESCRIBE_COLUMNS( HNDL, colCount, rec_tab);
    FOR i in 1..colCount
    LOOP
    IF Add_Equals_Sign > 0 AND i > 1 THEN
    fResult := ltrim( fResult || '=' || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
    ELSE
    fResult := ltrim( fResult || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
    END IF;
    END LOOP;
    IF Add_Equals_Sign > 0 THEN
    fResult := fResult ||'=';
    END IF;
    ELSE
    fResult := '!!COULD NOT OPEN CURSOR!!';
    fResult := P_SQL;
    END IF;
    RETURN fResult;
    --Tidy Up 
    DBMS_SQL.CLOSE_CURSOR(HNDL);
    Return 'EGG';
    END;
    --EXAMPLE USAGE
    --Select GET_COLUNS_AS_LIST
    --Select * from SALES_TYPE
    --', 1) FROM DUAL;

    So I have ended up with this.
    When I next get some time, I'd like to be able to strip out the table and simply output the results to an SQL Developer script window without having to go through the table.
    Now this works - but if you see that I am doing something wrong - please point it out.
    Many thanks,
    Ant
    CREATE OR REPLACE FUNCTION GET_COLUNS_AS_LIST( P_SQL IN CLOB, Add_Equals_Sign Number := 0)
    RETURN VARCHAR2
    IS
    fResult VARCHAR2(32000);
    HNDL NUMBER;
    d NUMBER;
    colCount INTEGER;
    i INTEGER;
    ChunkSize INTEGER;
    rec_tab DBMS_SQL.DESC_TAB;
    cCRLF VARCHAR(2) := CHR(13) || CHR(10);
    LONG_SQL dbms_sql.varchar2s;
    n INTEGER;
    l INTEGER;
    u INTEGER;
    StartPos INTEGER;
    BEGIN
    --INITIIALISE RESULT
    HNDL := 0;
    ChunkSize := 4;
    fResult := '';
    --fResult := fResult|| 'A'; 
    HNDL := DBMS_SQL.OPEN_CURSOR;
    --l := Length( P_SQL );
    l := dbms_lob.getLength( P_SQL );
    --l := 50;
    u := Round( l / ChunkSize ) + 1;
    --fResult := fResult|| 'B';   
    FOR n IN 1..u
    LOOP
    StartPos := ( ( n - 1 ) * ChunkSize ) + 1;
    IF StartPos = 0 THEN
    StartPos := 1;
    END IF;
    --LONG_SQL( n ) := SubStr( P_SQL, StartPos, ChunkSize );
    LONG_SQL( n ) := DBMS_LOB.SUBSTR( P_SQL, ChunkSize, StartPos );
    END LOOP;
    --fResult := fResult|| 'C';  
    if HNDL <> 0 THEN
    DBMS_SQL.PARSE ( c => HNDL,
    statement => LONG_SQL,
    lb => 1,
    ub => u,
    lfflg => false,
    language_flag => DBMS_SQL.NATIVE );
    --DBMS_SQL.PARSE( HNDL, P_SQL, DBMS_SQL.NATIVE);
    d := DBMS_SQL.EXECUTE( HNDL );
    DBMS_SQL.DESCRIBE_COLUMNS( HNDL, colCount, rec_tab);
    --fResult := fResult|| 'D';  
    FOR i in 1..colCount
    LOOP
    IF Add_Equals_Sign > 0 AND i > 1 THEN
    fResult := ltrim( fResult || '=' || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
    ELSE
    fResult := ltrim( fResult || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
    END IF;
    END LOOP;
    IF Add_Equals_Sign > 0 THEN
    fResult := fResult ||'=';
    END IF;
    ELSE
    fResult := '!!COULD NOT OPEN CURSOR!!';
    END IF;
    RETURN fResult;
    --Tidy Up 
    IF HNDL <> 0 THEN
    DBMS_SQL.CLOSE_CURSOR(HNDL);
    END IF;
    END;
    -- !!!!HOW TO USE THIS FUNCTION!!!!
    BEGIN
    EXECUTE IMMEDIATE ('DROP TABLE RPT_COLNAME_LOOKUPS;');
    COMMIT;
    EXECUTE IMMEDIATE ('CREATE TABLE RPT_COLNAME_LOOKUPS( COLUMN_NAME CLOB );');
    COMMIT;
    EXCEPTION WHEN OTHERS THEN NULL;
    END;
    DECLARE
    theSQL Clob;
    myresult CLOB;
    BEGIN
    --CLEAR OUT PREVIOUS RWS
    DELETE FROM RPT_COLNAME_LOOKUPS; COMMIT;
    --ASSIGN THE SQL TO RUN IT FOR 
    theSQL := '
    SELECT
    EVENT.EVENT_ID AS COCK_SUCKER,
    EVENT.EVENT_CODE, BLAH, BLAH, VERY LONG SQL STATEMENT';
    --CALL THE FUNCTION PASSING IN THE SQL AND IF I WANT THE = OR NOT
    SELECT GET_COLUNS_AS_LIST( theSQL, 1 ) INTO myresult FROM DUAL;
    --INSERT THE RESULTS INTO A TABLE SO WE CAN GRAB THEM
    INSERT INTO RPT_COLNAME_LOOKUPS SELECT myresult FROM DUAL;
    COMMIT;
    END;
    --THEN LOOK AT THE COLUMNS NAMES IN THIS TABLE
    --SELECT * FROM RPT_COLNAME_LOOKUPS;
    --#############################################################################

  • Select after anonymous blocks no INTO allowed

    hi
    I need to run an EXECUTE IMMEDIATE command to create a SEQUENCE in oracle sql 10g. I can only call EXECUTE IMMEDIATE between a BEGIN and a END; thus creating
    an anonymous block
    after the EXECUTE I need to do a select
    the problem is I get an error no matter what I have after the END;
    I cannot put the SELECT in the anonymous block because then I need to use INTO and I don't want to use INTO I just have to da a select
    can this be done in any way in oracle 10g(I am using the web interface) ?
    this is very frustrating for me as in mysql and ms sql this is sooooo simple and in oracle it looks impossible
    thank you in advance

    user10624880 wrote:
    so this cannot be done with oracle?
    the selects will return multiple rows what should I do with those rows
    I want them to appear on the screen when I run the script with the web interfaceSo you do want to actually capture the data and do something with it.
    If you are just running an SQL script through something like SQL*Plus you can just select the data and it will appear on the screen, but if you are doing it within PL/SQL code then you have to capture that data and output it via the appropriate means. Remember that PL/SQL is a process that is running on the database server so it doesn't have an interface to display data on for the user.
    You could select the data into an array structure (bulk collect), or use a select loop and then output it using something like DBMS_OUTPUT.PUT_LINE, assuming that your interface is going to read the DBMS_OUTPUT buffer and display the data.
    You haven't provided enough information about what you are really doing or the environment you are trying to run it through, for us to be able to give much more advice.
    As for whether it can be done with Oracle... yes it can, if you understand the concepts correctly. You can't just select data within PL/SQL and expect it to be displayed on your screen; as I said, the PL/SQL process on the database server knows nothing about your screen.

  • Customize the Anonymous Block.

    Hi All,
    DB - Oracle 9.2.0.1.0
    With the help of you Guys , I am able to create the Anonymous block.But, In the following BLOCK, I need to add One more functionality, if someone needs to grant "create view" privilge inside the block , then the massage should be " No direct grant allowed, this should be assigned to role. Also, is there any alternate, where we can achieve the same effect without using Associative
    DECLARE
    v_need_to_assign VARCHAR2(30) := '&ENTER PRIVILEGE ASSIGN';
    v_user varchar2(30) := '&USER';
    TYPE t_list IS TABLE OF NUMBER INDEX BY VARCHAR2(30);
    v_list t_list;
    v_chk NUMBER;
    e_fail_drop EXCEPTION;
    BEGIN
    v_list('SYSDBA') := 1;
    v_list('CREATE SESSION') := 1;
    BEGIN
    v_chk := v_list(v_need_to_assign);
    RAISE_APPLICATION_ERROR(-20001,'PRIVELEGE '||v_need_to_assign||' is not allowed to be grant');
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Privilege ' || v_need_to_assign|| ' Granted');
    EXECUTE IMMEDIATE 'GRANT '||v_need_to_assign || ' to ' || v_user;
    DBMS_OUTPUT.PUT_LINE('THE PRIVELEGE '||v_need_to_assign || ' HAS BEEN GRANTED TO ' || v_user) ;
    END;
    END;
    hare krishna

    I would appriciate, if you could offer your suggestions on this.
    hare krishna
    Alok

  • Dbms_profiler ANONYMOUS BLOCK issue

    Hi All,
    I am working on dbms_profiler to find out some expensive procedures in our application.
    But, when we check the output in table plsql_profiler_unitswe always found unit type and unit owner as ANONYMOUS BLOCK
    Then I tried something like:
    begin
    dbms_profiler.start_profiler('Test1');
    end;
    ---- Executed some procs manually
    begin
    dbms_profiler.stop_profiler();
    end;
    And the output is still showing as ANONYMOUS BLOCKin profiler tables. Can you please suggest when am I going wrong.

    Hi,
    in order to avoid side issues I recommend creating the profiler tables in the schema of the user that you are connected to when running the procedures.
    In my previous message I was suggesting to GRANT DEBUG on any objects that are now owned by the currently connected user.
    Let me summarize two typical scenarios:
    1. Database user SCOTT wants to profile his own procedures: in this case the best and easiest option is to create the three PLSQL_PROFILER_XXX tables in schema SCOTT and you don't need to grant anything, everything comes for free.
    2. Database user SCOTT wants to profile a procedure of his own that calls two procedures, one located in schema ABC and the other one in schema EFG. In this case user ABC must GRANT DEBUG ON proc_abc TO SCOTT and user EFG must GRANT DEBUG ON proc_efg TO SCOTT, otherwise these two procedures won't show up in the PLSQL profiler data (needless to say, both these procedures must have been granted also EXECUTE privilege to SCOTT).
    I also recommend that you do not create anything in schema SYS ever, so it would be advisable to drop those tables from schema SYS.
    Flavio
    http://oraclequirks.blogspot.com
    http://www.yocoya.com

  • Anonymous Block in PL/SQL

    How do we refer the anonymous block in PL/SQL? And what is the purpose of anonymous blocks?

    830933 wrote:
    How do we refer the anonymous block in PL/SQL? You cannot refer to a code unit by name, that has no name. A stored proc, stored function and stored package all have names. These are not only stored as a named object in the database, but if valid, also compiled and ready to be loaded and executed.
    An anonymous block has no name. So it cannot be stored as a named object in the database. You can store it in a column as a value for example. You can store it on the client as a SQL script file. Or the client can dynamically create anonymous blocks - as is the usual case.
    An anonymous block always need to be parsed and compiled before it can used.
    And what is the purpose of anonymous blocks?If your Visual Basic client need to execute a SQL statement, then the "anonymous SQL block" (which we simply call the SQL statement) that will be created and send to Oracle would look something as follows:
    select e.* from SCOTT.emp e where e.dept_no = :1Now anonymous PL/SQL blocks are not really different. Clients will typically create dynamic anonymous PL/SQL blocks for making PL/SQL procedural calls. Let's say your Visual Basic client wants to run procedure CalculateFoo( id in number, res out number ) that resides in the SCOTT schema in the database. It needs to create an anonymous PL/SQL block and place the procedure call in it.
    This anonymous block will look as follows:
    begin
      SCOTT.CalculateFoo( id => :1, res => :2 );
    end;It then needs to send this to Oracle to be parsed and executed. Oracle will also expect 2 bind variables to be supplied - an input bind variable called +1+ and an output bind variable called +2+.
    So all SQLs that you send are by default "anonymous" SQL blocks of code - that needs to be parsed and executed. Now PL/SQL works in a similar fashion - you will need to send a block of PL/SQL code (and not SQL code) in order to execute PL/SQL procedures and packages.

  • Execute proceduere from block

    Hi,
    We have oracle 10g On windows.
    we need to execute a procedure from anonimous block. requiement is like below
    if condition
    yes then execute procedure
    else
    do not execute procedure.
    How we can impliment this.

    968136 wrote:
    chanchal,
    just try this...
    here i have created on procedure and i am calling this procedure from anonymous block.
    create or replace procedure samp_block(date1 out varchar2)
    as
    begin
    select sysdate into date1 from dual;
    end;
    declare
    v_date date;
    v_no number:=1;
    begin
    if (v_no=1) then
    samp_block(v_date);
    dbms_output.put_line(v_date);
    else
    null;
    end if;
    end;
    Regards,
    Ramadurga
    Edited by: 968136 on Nov 2, 2012 3:37 PMHi Ramadurga,
    what is the reason to write something like:
    ELSE
       NULL;
    END IF;You can simply omit it the ELSE part.
    Regards.
    Al
    Edited by: Alberto Faenza on Nov 2, 2012 11:13 AM

Maybe you are looking for

  • Help:after amber update,Camera shut down....

    just after update to amber,my 920's camera never turn on, shut down when i turn it on.......what can i do? before amber it's ok..

  • Label help

    I have created a public application and placed all pages public with know authorisation required. Now all my label helps state "Unauthorized access." The labels work fine whilest I am logged in developing the application.

  • Import of data source into R/3 systems which are not in transport route

    Dear experts, I generated FI-SL data sources for hierarchies in order to extract a custom R/3 set hierarchy. The object directory entries are fine, the package has the correct assignment of the QA system. Now, I want to import the settings into anoth

  • TS1362 On one purchased album some songs stop half way through.

    Are these files corrupted? If so can I re-download working files?

  • Ipod not being found (WIndowsVista)

    Yea, so, I got a new laptop (HP Pavilion dv6000 w/Windows Vista), and when I plug my iPod into it, it doesn't recognize it at all. It will charge and thats it. It won't recognize on my bf's laptop either (same kind), but his iPod is fine on his and S