EXECUTE IMMEDIATE dynamic statement and return procedure value

Hello guys,
How can i return values from procedure using EXECUTE IMMEDIATE statment?
I made easy example:
CREATE OR REPLACE PACKAGE pac_test
IS
PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER,
v_out OUT NUMBER);
PROCEDURE pro_calc(p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER);
END;
CREATE OR REPLACE PACKAGE BODY pac_test
IS
PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER,
v_out OUT NUMBER)
IS
BEGIN
v_out:=(p_age_1+p_age_2+p_age_3)/3;
END pro_calc_average;
PROCEDURE pro_calc(p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER)
IS
x number;
v_sql varchar2(4000);
BEGIN
v_sql:='pac_test.pro_calc_average('||p_age_1||','||p_age_2||','||p_age_3||',x)';
dbms_output.put_line(v_sql);
EXECUTE IMMEDIATE v_sql;
dbms_output.put_line(' ====> '||x);
END pro_calc;
END;
-- Run procedures [Faild]
EXEC pac_test.pro_calc(2,9,19);
When i run:
DECLARE
x number;
BEGIN
pac_test.pro_calc_average(2,9,9,x);
dbms_output.put_line(' ====> '||x);
END;
It's works, but this is not what i am looking for.
Thank you guys,
Sam.

Hi Sam,
Like this?
CREATE OR REPLACE PACKAGE pac_test
IS
pac_var number;  /* added new*/
PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER,
v_out OUT NUMBER);
PROCEDURE pro_calc(p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER);
END;
CREATE OR REPLACE PACKAGE BODY pac_test
IS
PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER,
v_out OUT NUMBER)
IS
BEGIN
v_out:=(p_age_1+p_age_2+p_age_3)/3;
END pro_calc_average;
PROCEDURE pro_calc(p_age_1 IN NUMBER,
p_age_2 IN NUMBER,
p_age_3 IN NUMBER)
IS
pack_local_var number;
v_sql varchar2(4000);
BEGIN
--v_sql:='pac_test.pro_calc_average('||p_age_1||','||p_age_2||','||p_age_3||',x)';
v_sql:=' declare x number; begin pac_test.pro_calc_average('||p_age_1||','||p_age_2||','||p_age_3||',x);
dbms_output.put_line(x);
pac_test.pac_var:=x; /* added new*/
end;';
dbms_output.put_line(v_sql);
EXECUTE IMMEDIATE v_sql;
pack_local_var:=pac_var; /* added new*/
dbms_output.put_line(pack_local_var); /* added new*/
END pro_calc;
END;Declared a package variable.
But be aware this variable is accessible to everyone and they can read or change its value if they have the right privileges.
REgards,
Bhushan

Similar Messages

  • Bind Variable in SELECT statement and get the value  in PL/SQL block

    Hi All,
    I would like  pass bind variable in SELECT statement and get the value of the column in Dynamic SQL
    Please seee below
    I want to get the below value
    Expected result:
    select  distinct empno ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    100, HR
    select  distinct ename ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    TEST, HR
    select  distinct loc ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    NYC, HR
    Using the below block I am getting column names only not the value of the column. I need to pass that value(TEST,NYC..) into l_col_val variable
    Please suggest
    ----- TABLE LIST
    CREATE TABLE EMP(
    EMPNO NUMBER,
    ENAME VARCHAR2(255),
    DEPT VARCHAR2(255),
    LOC    VARCHAR2(255)
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (100,'TEST','HR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (200,'TEST1','IT','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (300,'TEST2','MR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (400,'TEST3','HR','DTR');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (500,'TEST4','HR','DAL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (600,'TEST5','IT','ATL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (700,'TEST6','IT','BOS');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (800,'TEST7','HR','NYC');
    COMMIT;
    CREATE TABLE COLUMNAMES(
    COLUMNAME VARCHAR2(255)
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('EMPNO');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('ENAME');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('DEPT');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('LOC');
    COMMIT;
    CREATE TABLE DEPT(
    DEPT VARCHAR2(255),
    DNAME VARCHAR2(255)
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('HR','HUMAN RESOURCE');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('MR','MARKETING');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    COMMIT;
    PL/SQL BLOCK
    DECLARE
      TYPE EMPCurTyp  IS REF CURSOR;
      v_EMP_cursor    EMPCurTyp;
      l_col_val           EMP.ENAME%type;
      l_ENAME_val       EMP.ENAME%type;
    l_col_ddl varchar2(4000);
    l_col_name varchar2(60);
    l_tab_name varchar2(60);
    l_empno number ;
    b_l_col_name VARCHAR2(255);
    b_l_empno NUMBER;
    begin
    for rec00 in (
    select EMPNO aa from  EMP
    loop
    l_empno := rec00.aa;
    for rec in (select COLUMNAME as column_name  from  columnames
    loop
    l_col_name := rec.column_name;
    begin
      l_col_val :=null;
       l_col_ddl := 'select  distinct :b_l_col_name ,pr.dept ' ||'  from emp pr, dept ps where   ps.dept like ''%IT'' '||' and pr.empno =:b_l_empno';
       dbms_output.put_line('DDL ...'||l_col_ddl);
       OPEN v_EMP_cursor FOR l_col_ddl USING l_col_name, l_empno;
    LOOP
        l_col_val :=null;
        FETCH v_EMP_cursor INTO l_col_val,l_ename_val;
        EXIT WHEN v_EMP_cursor%NOTFOUND;
          dbms_output.put_line('l_col_name='||l_col_name ||'  empno ='||l_empno);
       END LOOP;
    CLOSE v_EMP_cursor;
    END;
    END LOOP;
    END LOOP;
    END;

    user1758353 wrote:
    Thanks Billy, Would you be able to suggest any other faster method to load the data into table. Thanks,
    As Mark responded - it all depends on the actual data to load, structure and source/origin. On my busiest database, I am loading on average 30,000 rows every second from data in external files.
    However, the data structures are just that - structured. Logical.
    Having a data structure with 100's of fields (columns in a SQL table), raise all kinds of questions about how sane that structure is, and what impact it will have on a physical data model implementation.
    There is a gross misunderstanding by many when it comes to performance and scalability. The prime factor that determines performance is not how well you code, what tools/language you use, the h/w your c ode runs on, or anything like that. The prime factor that determines perform is the design of the data model - as it determines the complexity/ease to use the data model, and the amount of I/O (the slowest of all db operations) needed to effectively use the data model.

  • How crm visit the external website and return the value to crm

    how crm visit the external website and return the value to crm?
    Awen

    Can you elaborate the question? I assume that you are looking for some sort of mechanism to validate a customer's web site?
    Regardless of the scenario, the way to validate or retrieve a value from an external web site is to write a plugin that executes a WebRequest to the external site and reads the response.

  • SUBMIT and return the value of that report into internal table

    Dear all,
    I have a requirement. I want to submit a report and return the value of that report into my internal table.
    How to do this.
    Pl. guide.

    Hi Vidhya,
    Below links from SAP help will resolve your issue.
    http://help.sap.com/saphelp_nw04/Helpdata/EN/fc/eb3bde358411d1829f0000e829fbfe/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb3bd1358411d1829f0000e829fbfe/content.htm
    Edited by: Harsh Bhalla on Jan 2, 2010 11:54 AM

  • How to search two columns and return a value in the same row to a cell?

    Identification
    Diameter
    Soak
    3" Tank (inches/kft)
    AWG
    mils
    Code
    Strands
    Shield
    Conductor
    Insulation
    Semi-Con
    Days
    SD
    Injection
    Soak
    Total
    2
    175
    00
    7
    External
    0.288
    0.692
    0.752
    60
    0.4
    3.6
    20.0
    23.6
    2
    220
    00
    7
    External
    0.284
    0.764
    0.864
    75
    0.4
    3.6
    20.0
    23.6
    2
    260
    00
    7
    External
    0.284
    0.844
    0.944
    90
    0.4
    3.6
    21.8
    25.4
    2
    320
    00
    7
    External
    0.288
    0.964
    1.064
    110
    0.4
    3.6
    24.3
    27.0
    2
    345
    00
    7
    External
    0.288
    1.014
    1.114
    115
    0.4
    3.6
    25.6
    29.2
    Length
    3"
    4"
    AWG
    mils
    Soak
    SD
    Injection (3")
    Injection (4")
    650
    2
    320
    I want to input two values, AWG and mils and return the value in the Days column. 
    In the instance of what I am showing ....   AWG=2 AND mils=320 so Soak=110 ....
    I want to search the columns (AWG) AND (mils) to return a value in the column (Days) for that row into cell H10 (Soak)  ...
    So far I have toyed with LOOKUP, INDEX and MATCH ....

    SCW,
    I'm sure there is a clever way to cascade functions to avoid adding an auxiliary column in your practice table, but to me it wouldn't be worth the aggravation. I would add a column that concatenates Columns A & B, AWG & mils. This column can be anywhere and would be Hidden. Let's say your new column is Column N.
    In Column N, fill the body rows with:
    =A&"-"&B
    As good Numbers programming form would indicate, let's name the Practice Table Practices and only put the practices in that table. In another table where you do the lookup, let's call it Program, we will have the calculation/lookup.
    Based on your example, I'd guess that AWG may be in Column D and mils in Column E of your Program table, and the Soak lookup in Column F. If I'm wrong, adjust the column id.
    In Column F, write:
    =OFFSET(Practices::I$1,MATCH(D&"-"&E, Practices::N,0)−1, 0)
    The hyphen in the concatenated representation of the combination of AWG and mils is just tp make it more readable.
    As I'm sure you know, you could use other approaches, but since I had you put your aux column at the end of your Practices table, OFFSET with MATCH is a clean approach. INDEX could be used too.
    Here's an illustration:
    Regards,
    Jerry

  • Mutator to compute set and return the value

    Hi
    I am having trouble working out how to do a mutator that does all three
    compute a value set the value and then return it this is what i have so far
    this example calculates and returns the value but does it set the value of totalSlices ???? this is the best option so far
    public int totalSlices (){
    int total = meatSlices + vegSlices;
    return (int) total;
    this one seems more likely to me but unsure is this a set method as well
    public insert (int fiveC)
    fiveCentCoin += fiveC;
    returne fiveCentCoin;
    this is the final example i have come up with but dont know if it sets the value as well
    public int calculateCost () {
    double cost;
    if (age==0) {
    age = 0.1;
    if (neutered) {
    cost = (100/age) + (stay * 3) + SHOTS + TAGS;
    } else {
    cost = (100/age) + (stay * 3) + SHOTS + TAGS + NEUTER;
    return (int) Math.round (cost);
    the problem i face i am not sure of how to combine a mutator calculation, set method and return it all in one i havnt done that before and cannot find an example
    thanks

    I think you're trying to take a hollistic approach to programming. That won't work.
    You need to go back and get a good understanding of exactly what each element of Java does.
    Sylvia.

  • Problem wile EXECUTE IMMEDIATE DDL statement in procedure

    Hi ,
    This is my procedure and it's getting compiled but while executing procedure getting this error,
    can anyone please tell me how to fix this?
    create or replace procedure construct_Table (name_table IN VARCHAR2)
    IS
    v_tab_name varchar2(40):=NULL;
    v_sql_Stmt varchar2(32767) := NULL;
    finalquery varchar2(32767) :=NULL;
    cursor tp is
    select COLUMN_NAME,DATA_TYPE,DATA_PRECISION,CHAR_LENGTH  from all_tab_cols where table_name=name_table;
    BEGIN
    begin
    select TABLE_NAME into v_tab_name from user_tables where table_name=name_table;
    EXCEPTION
    WHEN no_Data_found
    THEN
    DBMS_OUTPUT.PUT_LINE('No such table exist');
    end;
    if(v_tab_name IS NOT NULL)then
    finalquery := 'CREATE TABLE '||v_tab_name||'_DUMMY (';
       FOR I IN tp LOOP
       if(I.data_type='VARCHAR2') then
       v_sql_stmt := finalquery ||I.column_name||' '||I.data_type||'('||I.char_length||') ';
       elsif(I.data_type='NUMBER') then
       v_sql_stmt := finalquery ||I.column_name||' '||I.data_type||'('||I.DATA_PRECISION ||') ';
       else
       v_sql_stmt := finalquery ||I.column_name||' '||I.data_type ;
       end if;
       finalquery := v_sql_stmt || ',';
       END LOOP;
       finalquery := SUBSTR(finalquery,1,LENGTH(finalquery) - 1)||')';
       dbms_output.put_line(finalquery);
       EXECUTE IMMEDIATE'grant create any table to cmsuser';
       EXECUTE IMMEDIATE finalquery;
    end if; 
    END;
    /This is the error I am getting
    Error starting at line 1 in command:
    begin
    construct_Table ('EMP');
    end;
    Error report:
    ORA-01031: insufficient privileges
    ORA-06512: at "CMSUSER.CONSTRUCT_TABLE", line 30
    ORA-06512: at line 2
    01031. 00000 -  "insufficient privileges"
    *Cause:    An attempt was made to change the current username or password
               without the appropriate privilege. This error also occurs if
               attempting to install a database without the necessary operating
               system privileges.
               When Trusted Oracle is configure in DBMS MAC, this error may occur
               if the user was granted the necessary privilege at a higher label
               than the current login.
    *Action:   Ask the database administrator to perform the operation or grant
               the required privileges.
               For Trusted Oracle users getting this error although granted the
               the appropriate privilege at a higher label, ask the database
               administrator to regrant the privilege at the appropriate label.Thanks ,
    Deekay.

    Deekay,
    If you grant create table privilege and create table in the same procedure, then how you will differentiate that which user you granted the privilege and in which schema, you are creating the table. Here, you are granting to "cmuser", but in the same schema, you are creating the table also. How can a user grant privilege to himself?
    Login as DBA, grant create any table privilege to "cmuser" from dba. Then, you can execute you procedure in "cmuser" schema.

  • I want a select statement to return two values, sum of one column and customer number

    I have two columns one called invoice_number and the other invoice_amount. I want a select statement to return two columns.... invoice_number and then the sum of the invoice_amount(s) for each unique invoice number.
    SELECT sum(invoice_amount) AS Totalinvoice_amount FROM InvoiceTB where invoice_number = 'INV102'
    This is where I've started, which returns:
    Totalinvoice_amount
    500.00
    Any help is appreciated.
    Please mark my post as helpful or the answer or better yet.... both! :) Thanks!

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Help on Execute Immediate Dynamic Sql

    Hi all
    when i run the following Pl/SQL,nothing is happening
    I want to pass array to following procedure
    DECLARE
    SQL_STMT      VARCHAR2(1000);
    BEGIN
    SQL_STMT  := 'Select '|| '''populate_table_test(''' || '|| chr(39)||id_name||chr(39)||' ||''','''||'|| chr(39)||attribute1||chr(39)||' ||''','''||'|| chr(39)||attribute2||chr(39)||' ||''');'''||' from table_test1';
    dbms_output.put_line(sql_stmt);
    execute immediate sql_stmt;
    Exception when others then
    dbms_output.put_line(sqlerrm);
    end;
    SQL> ed
    Wrote file afiedt.buf
      1  Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
      2  chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
      3* table_test
    SQL> /
    'POPULATE_TABLE_TEST('||CHR(39)||ID_NAME||CHR(39)||','||CHR(
    populate_table_test('AAA','AA','AA');
    populate_table_test('AAA','AA','AA');
    CREATE
      TABLE TABLE_TEST1
        "ID_NO"      NUMBER(10,0)     ,
        "ID_NAME"    VARCHAR2(10 BYTE),
        "ATTRIBUTE1" VARCHAR2(10 BYTE),
        "ATTRIBUTE2" VARCHAR2(10 BYTE)
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    commit;
    CREATE TABLE TABLE_TEST
    (ID_NO NUMBER(10) ,
    id_NAME VARCHAR2(10) ,
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    select * from "TABLE_TEST";
    CREATE OR REPLACE TYPE T_TYPE IS OBJECT (
    id_NAME VARCHAR2(10),
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    Create or replace  type TB_T_TYPE as varray(200) of  T_TYPE ;
    CREATE OR REPLACE
    PROCEDURE POPULATE_TABLE_TEST (EXAMPLE IN TB_T_TYPE) AS
    begin
    FOR I IN 1..EXAMPLE.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ID_NAME);
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE1);
    DBMS_OUtPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE2);
    insert into TABLE_TEST(id_name,attribute1,attribute2)
    values (treat(example(i) as T_TYPE).id_NAME,
    treat(example(i) as T_TYPE).ATTRIBUTE1,
    treat(example(i) as T_TYPE).ATTRIBUTE2
    end loop;
    end; Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
    chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
    table_test
    Edited by: user1849 on Nov 30, 2011 12:40 PM
    Edited by: user1849 on Nov 30, 2011 1:18 PM

    user1849 wrote:
    Hi all
    when i run the following Pl/SQL,nothing is happeningRemember to issue the SQL*Plus command
    SET  SERVEROUTPUT  ONbefore running it; otherwise, you won't see the output from dbms_output.
    >
    I want to pass array to following procedureIs this a procedure or an anonymous PL/SQL block?
    If it's a procedure, post the entire procedure, starting with CREATE [OR REPLACE] PROCEDURE...
    Never write, let alone post, unformatted code. Indent the code to show the scope of BEGIN, LOOP, etc.
    DECLARE
    SQL_STMT      VARCHAR2(1000);
    BEGIN
    SQL_STMT  := 'Select '|| '''populate_table_test(''' || '|| chr(39)||id_name||chr(39)||' ||''','''||'|| chr(39)||attribute1||chr(39)||' ||''','''||'|| chr(39)||attribute2||chr(39)||' ||''');'''||' from table_test1';
    dbms_output.put_line(sql_stmt);
    execute immediate sql_stmt;
    Exception when others then
    dbms_output.put_line(sqlerrm);
    end;
    /Only use an EXCEPTION handler when you can improve on the default error handling. The default is to print an error message, so there's no point in you explicitly doing the same.
    Why do you need dynamic SQL? Post the output results you want to get from the sample data you posted.
    Given that you do need dynamic SQL, why can't you use bind variables, rather than including the values as literals?
    Given that you have to use literals, use Q-notation for strings that include single-quote characters.
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements003.htm#sthref337
    For example:
    ...     SQL_STMT  := Q{'Select  populate_table_test ('}'
              || id_name
              || Q'{','}'
              || attribute1
              || Q'{','}'
    SQL> ed
    Wrote file afiedt.buf
    1  Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
    2  chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
    3* table_test
    SQL> /
    'POPULATE_TABLE_TEST('||CHR(39)||ID_NAME||CHR(39)||','||CHR(
    populate_table_test('AAA','AA','AA');
    populate_table_test('AAA','AA','AA');
    CREATE
    TABLE TABLE_TEST1
    "ID_NO"      NUMBER(10,0)     ,
    "ID_NAME"    VARCHAR2(10 BYTE),
    "ATTRIBUTE1" VARCHAR2(10 BYTE),
    "ATTRIBUTE2" VARCHAR2(10 BYTE)
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    commit;
    Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful.
    Is that the best sample data for testing? Wouldn't it be better to have at least one row that was not the same as all the others?
    CREATE TABLE TABLE_TEST
    (ID_NO NUMBER(10) ,
    id_NAME VARCHAR2(10) ,
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    select * from "TABLE_TEST";
    CREATE OR REPLACE TYPE T_TYPE IS OBJECT (
    id_NAME VARCHAR2(10),
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    Create or replace  type TB_T_TYPE as varray(200) of  T_TYPE ;
    CREATE OR REPLACE
    PROCEDURE POPULATE_TABLE_TEST (EXAMPLE IN TB_T_TYPE) AS
    begin
    FOR I IN 1..EXAMPLE.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ID_NAME);
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE1);
    DBMS_OUtPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE2);
    insert into TABLE_TEST(id_name,attribute1,attribute2)
    values (l_t_seq(i),
    treat(example(i) as T_TYPE).id_NAME,
    treat(example(i) as T_TYPE).ATTRIBUTE1,
    treat(example(i) as T_TYPE).ATTRIBUTE2
    end loop;
    end; You're trying to INSERT 4 values into 3 columns. Did you mean to say "insert into TABLE_TEST( *id_no,* id_name,attribute1,attribute2)"?
    What is l_t_seq? Post complete test scripts that people can run to re-create the problem and test their ideas.

  • Execute Immediate with SQL in Stored Procedure

    Dear Experts, Please help / guide on below statement which i want to execute in stored procedure,
    EXECUTE IMMEDIATE 'INSERT INTO TABLE
    SELECT COUNT(AGENTID) FROM TABLE_1 A,
    TABLE_2 B, TABLE_3 C
    WHERE A.COL = B.COL AND B.COL = C.COL AND
    DT BETWEEN TRUNC(SYSDATE-1) + 1/24 + 0/12/60/60 AND TRUNC(SYSDATE-1) + 25/24 - 0/12/60/60';
    Edited by: DBA on Dec 3, 2011 3:57 PM

    So what's the problem? The only thing I can see is:
    INSERT INTO TABLETABLE is reserved word, so name your table differently.
    Also, I am assuming the above statement is actually generated from some variables based on some conditions, otherwise why would you need dynamic SQL, just issue:
    INSERT INTO TABLE
    SELECT COUNT(AGENTID) FROM TABLE_1 A,
    TABLE_2 B, TABLE_3 C
    WHERE A.COL = B.COL AND B.COL = C.COL AND
    DT BETWEEN TRUNC(SYSDATE-1) + 1/24 + 0/12/60/60 AND TRUNC(SYSDATE-1) + 25/24 - 0/12/60/60;

  • Whats the difference between producing output and returning a value?

    I've just started learning Java. I am having difficulty understanding what it means to "return a value".
    If a method has an argument, then whenever this method is called the variable named will be used for output.
    If you create a method to return a new value rather than display it, you would exchange the 'void' for 'double' e.g. public static double predictRaise(double moneyAmount). My book states that a return statement causes a value to be sent from a called method back to the calling method. Their example is not clear to me. Here is what they show for when only 'output' is produced:
    <code>
    Public static void predictRaiseUsingRate (double money, double rate)// 2 arguments
              double newAmount;
              newAmount = money * (1 + rate);
              System.out.println (?With raise, new salary is ? + newAmount);
    </code>
    And their example of a returned value:
    <code>
    public static double predictRaise(double moneyAmount)
              double newAmount;     
              newAmount = moneyAmount * 1.10;
              return newAmount;
    </code>
    Their explanation: "This return statement causes a value to be sent from a called method back to the calling method. The value stored in newAmount is      sent back to any method that calls predictRaise() method."
    For some reason this is just not sinking in. Does anyone have a better example/explanation? I could not find anything with a better explanation in archives.
    Are they tring to tell me: "if the original method declares an argument that is declared as 257 in the method call, that when that same method is called again, it will always be 257? But if you do a return statement, any changes in the return statement will now always be used in all methods calling that method?
    Thanks for your help.
    Gizelle

    To use an older and possibly more easily understood terminology. Methods can either be "functions" almost in the mathematical sense or they can be "procedures" in the sense of a process.
    A function is a mapping between a "domain", its arguments, and a "range", its result. An example of a function in mathematics is cosine, which takes an argument in degrees or radians and returns a result between -1 and 1. In java functions are just methods that declare a result type. eg. public int foo(int arg).
    A procedure is a program that doesn't return any result, it's not something that fits well into mathematics, but it occurs all the time in real life. For example, walking the dog does not map something from a domain to a range, but it may have some side effects, which is why I always carry a plastic bag with me. Procedures in java are methods that are declared as "void". eg. public void foo(int arg).
    All the well known arithmetic operations are functions, they take one or two arguments in the domain of numbers and return a result in the same set. Eg, x = a + b, the operator + is a function that takes two numbers, calculates the arithmetic sum of them and returns a result. Functions are very handy since you can string them together, eg. z = a+foo(b)*max(c+d). This doesn't work with procedures.
    Procedures are often used for much longer and more involved operations, there is no immediate result, but a lot of things may occur while they run. Data may be printed on a screen or paper, a database or file may get updated and email messages might get send. But no other expession is waiting for a resulting value so it can carry on. Procedures may also happen asynchonously, ie. outside the timeframe of their caller, see threads. Functions cannot do this, or if they do, they turn into procedures by throwing away their result. For example, you can schedule a procedure to send an email to your friends every Friday inviting them to go out for drinks, but you don't wait around for the result.
    In a way functions are a bit like phone calls, you wait for a response, procedures are more like snail mail, you send it off and check on what happened later.
    I hope this helps.

  • How execute a dynamic statement with a variable number of bind variables

    Hi all.
    I would like to execute SQL statements in a PL/SQL function.
    SQL statements must use bind variable in order to avoid parsing time. But the number of arguments depends on the context. I can have from 10 to several hundreds of arguments (these arguments are used in a 'IN' clause).
    To minimise the number of differents signature (each new signature involve a parsing), the number of argument is rounded.
    My problem is : how to set dynamicaly the bind variables ?
    Cause it is pretty simple to construct dynamicaly the SQL statement, but using an
    " OPEN .... USING var1, var2, ..., varX "
    statement, it is not possible to handle a variable nomber of bind variable.
    I am looking for the best way to do the same thing that it can be done in java/JDBC with the PreparedStatement.setObject(int parameterIndex, Object x).
    I saw the dbms_sql package and bond_variable procedure : is a the good way to do such a thing ?
    Thanks

    If the variation is only values in an IN list, I would suggest using an object type for the bind variable. This lets you have just one bind variable, regardless of how many values are in the IN list.
    The dynamic SQL ends up looking like:
    ' ... where c in (select * from table(:mylist))' using v_list;where v_list is a collection based on a SQL user-defined type that can be populated incrementally, or in one shot from a delimited list of values using a helper function.
    I use this approach all the time in dynamic searches.
    See this link for more details:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:110612348061

  • Dyn sql execute immediate  A plsql block returning sql%rowcount of rows inserted

    I would like to get the number of rows inserted in a dynamic sql statement like following.
    execute immediate
    'begin insert into a(c1,c2,c3)
    (select ac1,ac2,ac3 from ac where ac1=:thekey
    UNION select tc1,tc2,tc3 from tc where tc1=:otherkey); end;' using in key1,in key2;
    I have tried per the oracle8i dyn sql chapter in doc RETURN sql%rowcount won't compile.
    also add this to statement 'returning sql%rowcount into :rowcount'
    no luck.
    any ideas.?
    thanks.

    Quick comment first - I'm not sure why you are even using dynamic SQL here. There is nothing dynamic about your statement. It is equivalent to just:
    insert into a (c1, c2, c3)
      select ac1, ac2, ac3
        from ac
       where ac1 = key1
      UNION
      select tc1, tc2, tc3
        from tc
       where tc1 = key2;Unless you are really dynamically changing a table or column name here and just didn't show it in your example, you certainly don't want the overhead of NDS for this insert in this situation.
    In any case, you just need to evaluate SQL%ROWCOUNT in the next statement.
    insert ...;
    if sql%rowcount = 0 then
      -- nothing was inserted
    end if;

  • Collable statement and stored procedure problem

    Hi,
    I am using a collable statement to execute a stored procedure.
    The stored procedure is a bit complex since it uses a function to retrieve sequence nextval (newId),
    than insert a row and returns the newId.
    Anyway, I checked it with sql plus and it works, but when trying to execute it from my Java code, I get the following error message:
    java.sql.SQLException: ORA-06550: line 1, column 33:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    . ( ) , * @ % & | = - + < / > at in mod not range rem => ..
    <an exponent (**)> <> or != or ~= >= <= <> and or like
    between is null is not || indicator is dangling
    The symbol ")" was substituted for ";" to continue.
    Anyone can help?
    Thanks,
    Michal

    My PL/SQL code:
    CREATE OR REPLACE FUNCTION getNotifSeq RETURN NUMBER
    IS
    newId NUMBER;
    BEGIN
         SELECT NOTIFICATION_SEQ.NEXTVAL INTO newId FROM DUAL;
    RETURN newId;
    END;
    run
    CREATE OR REPLACE PROCEDURE insertNotifMsg (
    sentBy IN VARCHAR,
    subject IN VARCHAR,
    msg IN VARCHAR,
    newId OUT NUMBER)
    IS
    BEGIN
    newId := getNotifSeq;
    INSERT INTO NOTIFICATIONS(NOTIF_ID,SENT_BY,SUBJECT,MSG)
    VALUES(newId,sentBy,subject,msg);
    END insertNotifMsg;
    run;
    My Java code to call the procedure:
    try
    conn = myDBconn.getConnection();
    CallableStatement callStmt = conn.prepareCall("{call insertNotifMsg(?,?,?,?}");
    callStmt.setString(1,notif.getSentBy());
    callStmt.setString(2,notif.getSubject());
    callStmt.setString(3,notif.getMsg());
    callStmt.registerOutParameter(4, Types.INTEGER);
    ResultSet rs = callStmt.executeQuery();
    if (!rs.next()) {
    throw new SQLException("ERROR: Notification was not inserted into database!");
    long newId = callStmt.getInt(4);
    callStmt.close();
    notif.setNotifId(newId);
    conn.commit();
    callStmt.close();
    finally
    myDBconn.closeConnection(conn);
    Thanks,
    Michal

  • Execute immediate issue while calling a procedure from plsql block

    Hi all,
    I have the following simple code ,my execute immediate is not working(I am pasting the error below as well)
    CREATE OR REPLACE PROCEDURE CALL_RAHUL_PROCEDURES
    AS
    strng varchar2(1000);
    BEGIN
    for i in (select proc_name,flag,id from rahul_procedures order by id)
    loop
    if (i.flag = 'Y')
    then
    strng := 'exec '||i.proc_name||'(''rahul'')';
    dbms_output.put_line(strng);
    execute immediate strng;
    end if;
    end loop;
    END CALL_RAHUL_PROCEDURES;
    Error:
    Connecting to the database INQDWD.
    ORA-00900: invalid SQL statement
    ORA-06512: at "ETLADMIN.CALL_RAHUL_PROCEDURES", line 17
    ORA-06512: at line 2
    exec RAHUL_HELLO_WORLD2('rahul');
    Process exited.
    Disconnecting from the database INQDWD.
    data in rahul_procedures table :
    Proc_name flag Id
    RAHUL_HELLO_WORLD     N     1
    RAHUL_HELLO_WORLD2     Y     2
    RAHUL_HELLO_WORLD     N     3
    RAHUL_HELLO_WORLD3     N     4
    please help.
    Regards
    Rahul

    Mac_Freak_Rahul wrote:
    Well I have to call 26 procedures one by one and the names of the procedures would be in a table'rahul_procedures' Which is 100% wrong.
    Data is stored in tables, program code is stored in procedures or view defintions.
    http://en.wikipedia.org/wiki/Data_%28computing%29
    >
    Data vs programs
    Typically, different files are used to store programs vs data. Executable files contain programs; all other files are data files.
    >
    So you have just violated the primary distinction between data and program code.
    I dont find anything strange in my question,Only because you do not appear to know what you are doing or the difference between data and program code.
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1943344500346351703
    >
    ugh, what an ugly "design". I can see your life will be full of performance issues, strange 'bugs', and other unpleasant side effects. I mean, it all looks "so cool", but it'll be a nightmare to maintain and enhance.
    but then you have the issue of binds, which will be intractable. You'd have to know the binds at compile time, but you have hidden all of your sql in a magic generic table - so you cannot possibly know your binds at compile time.
    I would suggest you discard all of this code (I am DEAD SERIOUS) and start over. This is a bad idea from the get go. Or at least do me a favor and do not use plsql (you make it look like a good database implementation, but it isn't)
    The objective here is to store SQL Statements in a Table(a sql repository) and just call the required SQL from the application using the sqlid using the sql_execute procedure. ...
    CHANGE YOUR OBJECTIVE.
    How about this for a good objective:
    the objective here is to store sql statement in a plsql routine (a sql repository, you call a procedure and we run sql) and just call the required sql form the applicatoin using the STORED PROCEDURE
    sorry, can I think of hacks to get you going? yes, application contexts come to mind - a fixed number of binds comes to mind. Am I going to work them out? No - it is the wrong way to approach a database application.

Maybe you are looking for