Problem in using table name dynamically in PL/SQL

I tried to create a procedure to use table name dynamically and got the following error. Anything wrong with my procedure?
NFADV>declare
  2   cnt number;
  3   cursor cur is select table_name from user_tables where table_name in ('EMP','DEPT');
  4  begin
  5   for c1 in cur
  6   loop
  7    execute immediate select count(*) into cnt from c1.table_name;
  8      dbms_output.put_line('Count is : '||cnt);
  9   end loop;
10  end;
11  /
declare
ERROR at line 1:
ORA-06550: line 7, column 21:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
( - + case mod new not null <an identifier>
<a double-quoted delimited-identifier> <a bind variable> avg
count current exists max min prior sql stddev sum variance
execute forall merge time timestamp interval date
<a string literal with character set specification>
<a number> <a single-quoted SQL string> pipe
<an alternatively-quoted string literal with character set specification>
<an alternatively-quo
ORA-06550: line 8, column 5:
PLS-00103: Encountered the symbol "DBMS_OUTPUT"
ORA-06550: line 8, column 45:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
. ( , * % & - + / at mod remainder rem <an identifier>
<a double-quoted delimited-identifier> <an exponent (**)> as
from into || multiset bulkThanks and Regards
Kaustubh

Hi,
The wrong part is in execute immediate, it should be as follows:
execute immediate ('select count(*) from '|| c1.table_name)
into cnt
(not tested)
Regards
AK

Similar Messages

  • How to use table name dynamically in report  procedure

    Hello every body
    I want to use table name dynamically means at runtime i want to pass table name.
    I can do this by lexical parameter in main query.
    But my problem is that i want to crate new format trigger or new function that use 1 cursor in which that lexical parameter : table name is used.
    so how to do that?
    i can not use that lexical parameter it is giving error.
    please help me how to do that.

    Call a database function which you pass the lexical parameter. Then in the database function you use dynamic sql or the execute immediate option to build the SQL string.
    Return the information from this function to build your business logic on in your format trigger.
    Marcos

  • Using Table name in Read statement dynamically

    Hi Experts,
    I have the following requirement.
    Based on a country code say "A" , "B", "C" and based on this i have to read different internal tables lt_tabA, lt_tabB and lt_tabC.
    The table key can be given dynamically, but how can i use the internal table name dynamically without using if statements.
    Please help.
    Thanks!
    Best Regards,
    Gayathri

    Hi Gayathri,
    something like
    DATA:
        lt_t100 TYPE TABLE OF t100,
        lt_t000 TYPE TABLE OF t000.
      FIELD-SYMBOLS:
        <table> TYPE table,
        <rec>   TYPE ANY,
        <field> TYPE ANY.
      SELECT:
        * INTO CORRESPONDING FIELDS OF TABLE lt_t100 FROM t100 UP TO 10 ROWS,
        * INTO CORRESPONDING FIELDS OF TABLE lt_t000 FROM t000 UP TO 10 ROWS.
      CASE abap_true.
        WHEN space.
          ASSIGN  lt_t100 TO <table>.
        WHEN OTHERS.
          ASSIGN  lt_t000 TO <table>.
      ENDCASE.
      READ TABLE <table> with key ('MANDT') = sy-mandt ASSIGNING <rec>.
    Regards,
    Clemens

  • How to pass the table name dynamically in xml parsing

    Hi All,
    I have created one procedure for parsing xml file which is working perfectly.
    FORALL i IN t_tab.first .. t_tab.last
             INSERT INTO Test_AP VALUES t_tab(i);Now I want to put the table name dynamically+. For that I have added one query and modify above code as follow:-
    I have already declare dml_str varchar2(800) in declaration part.
    Query is as follows:-
    select table_name into tab_name from VERSION_DETAILS where SUBVERSION_NO=abc;  -- here abc is variable name which contains values.
    FORALL i IN t_tab.first .. t_tab.last
              dml_str := 'INSERT INTO ' || tab_name || ' values :vals';
              EXECUTE IMMEDIATE dml_str USING t_tab(i);But it's not working. How I will resolve this or through which way I achieved the intended results. Anyone can guide me on this matter.
    Thanks in advance for your help...

    Hi,
    But it's not working.Don't you think it would help to give the error message?
    Put the assignment before FORALL.
    FORALL only accepts one subsequent DML statement (static or dynamic SQL) :
    dml_str := 'INSERT INTO ' || tab_name || ' values :vals';
    FORALL i IN t_tab.first .. t_tab.last          
    EXECUTE IMMEDIATE dml_str USING t_tab(i);

  • How to find the list of un used table names in a schema?

    Hi,
    I have a doubt in Oracle. The doubt is that If we are using any tables in Function Or Proc.... Then...We can list all those used table names from USER_DEPENDENCIES system table. Right...
    But, If the table is used with Execute Immediate Statement, then, those table names are not coming out with USER_DEPENDENCIES system table. Because they are identified at run time and not compile time.
    It is fine. And I agree.. But, If I want to list out those tables also...then...How to do? Any idea?
    I think ‘USER_SOURCE’ system table may not be the right one. If there is any other system table avails for this purpose...then..it would be very grateful to extract right...
    So I am wanting that exact system table.
    Please let me know about this, if you have any idea or check with your friends if they have any idea.
    Regards,
    Subramanian G

    Hi Guys,
    Thanks for all your answers.
    Yes....You are all right. We can list out the used tables upto certain extent. Anyhow, I have done some R&D to derive the SQL's which is given below:
    SELECT TABLE_NAME FROM USER_TABLES
    MINUS
    SELECT DISTINCT UPPER(REFERENCED_NAME)
    FROM user_dependencies
    where
    referenced_type='TABLE' and UPPER(NAME) in
    select distinct UPPER(object_name) from user_objects where UPPER(object_type) in
    'MATERIALIZED VIEW',
    'PACKAGE',
    'PACKAGE BODY',
    'PROCEDURE',
    'TRIGGER',
    'VIEW',
    'FUNCTION'
    UNION
    SELECT UT.TABLE_NAME FROM
    SELECT TABLE_NAME FROM USER_TABLES
    MINUS
    SELECT DISTINCT UPPER(REFERENCED_NAME)
    FROM user_dependencies
    where
    referenced_type='TABLE' and UPPER(NAME) in
    select distinct UPPER(object_name) from user_objects where UPPER(object_type) in
    'MATERIALIZED VIEW',
    'PACKAGE',
    'PACKAGE BODY',
    'PROCEDURE',
    'TRIGGER',
    'VIEW',
    'FUNCTION'
    AND REFERENCED_OWNER=(SELECT sys_context('USERENV', 'CURRENT_SCHEMA') FROM dual)
    ) UT,
    ( SELECT * FROM USER_SOURCE
    WHERE NAME IN
    ( SELECT DISTINCT NAME FROM USER_SOURCE
    WHERE TYPE NOT IN ('TYPE')
    AND
    UPPER(TEXT) LIKE '%EXECUTE IMMEDIATE%'
    ) US
    WHERE
    UPPER(US.TEXT) LIKE '%'||UPPER(UT.TABLE_NAME)||'%'
    AND
    (UPPER(US.TEXT) NOT LIKE '%--%')
    The above SQL Query can list out unused tables by checking the Dynamic SQL Statement also upto some level only.
    Once we extracted the list of unused tables, having a manual check would be also greater to verify as it is should not impact the business applications.
    Regards,
    Subramanian G

  • Unable to  use Table name in a variable

    Hi,
    I am trying to build a select statement which uses table name in a variable. Please help me in building such statements.
    Regards
    Kishore

    Hi,
    I am trying to build a select statement which uses table name in a variable. Please help me in building such statements.
    Regards
    Kishore

  • Member acces profile error(A table name, specified in an sql command)

    Hi friends,
    In my bpc application(A) below 3 dims are secure dims.
    1. entiiy  (std)
    2. category (std)
    3. location (custom dim)
    while defining one member access profile,
    Read Only      : CATEGORY 100
    Read & Write      : CATEGORY 200,500
    for whatever combinatio i use, for other secure dims (eg: category,location where base member,or parent members ) i'm getting below error  message
    A table name, specified in an sql command, is unknown.
    We are on bpc75nw sp04.
    Pls suggest us .
    dump(st22):
    Short text
        A table name, specified in an SQL command, is unknown.
    What happened?
        Error in the ABAP Application Program
        The current ABAP program "CL_UJE_MEMACCESS_CACHE========CP" had to be
         terminated because it has
        come across a statement that unfortunately cannot be executed.
    Error analysis
        An exception occurred that is explained in detail below.
        The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SEMANTICS', was
         not caught in
        procedure "REMOVE_MEMACCESS" "(METHOD)", nor was it propagated by a RAISING
         clause.
        Since the caller of the procedure could not have anticipated that the
        exception would occur, the current program is terminated.
        The reason for the exception is:
        An invalid table name "/1CPMB/RDWCSUMAS" was specified in an Open SQL command:
        Due to one of the following reasons, the error occurs only at runtime:
        - the table name was specified dynamically, or
        - the SELECT clause, WHERE clause, GROUP-BY clause, HAVING clause, or
          ORDER-BY clause was specified dynamically.
    Thanks,
    naresh
    Edited by: Naresh P on Feb 19, 2011 10:40 AM

    Hi Naresh,
    As far as I know You have specify Explicit Access to all the dimensions mentioned as Secured in your Application.
    You can't skip the secured Dimesions.
    In your case if you want to restrict only one dimension for 1 Member Access Profile then give Read & Write access to other 2 Dimensions and select ALL members.
    This might solve your problem.
    Hope it helps.
    Chaithanya

  • ODI: Using Table Name in Dynamic filters

    We have a requirement, where the filters have to be dynamically generated and applied on the source system data stores.
    The requirement can be best explained by the below example.
    I have EMPLOYEE and DEPARTMENT table as the source datastores and EMP_DEPT (flat table) as the target datastore.
    The filter condition will be updated now and then by the admin in a table. They would like to run the integration interface with the condition mentioned in the table.
    Metadata table and sample data: (DY_FILTERS)
    TABLE_NAME | INTERFACE_NAME | CONDITION
    EMPLOYEE | EMP_DEPT | EMPLOYEE.EMPLOYEE_NAME LIKE 'A%'
    DEPARTMENT | EMP_DEPT | DEPARTMENT.DEPARTMENT_ID = 10
    So now the interface has to run with the conditions 'EMPLOYEE.EMPLOYEE_NAME LIKE 'A%' and DEPARTMENT.DEPARTMENT_ID = 10.
    To achieve, the best possible solution I can think of is, I have defined a variable for the dynamic filter and under the refresh section and I am planning to use the following query:
    SELECT CONDITION FROM DY_FILTERS WHERE INTERFACE_NAME = <%=odiRef.getPop("POP_NAME")%> AND
    TABLE_NAME = ***************.
    I was able to pick the interface that is currently involved by using getPop() method where as I dont have clue for getting the table name.
    Please share with me, if you have answer. Also if you have any other way to achieve this, please share the same.
    Note: The actual scenario is more complex than the example given above. But the crux of the requirement is very well covered in the example.
    Edited by: 986046 on Feb 14, 2013 2:06 PM

    Hi,
    If you've only one source datastore in your interface, you can retrieve it's name with <%=odiRef.getSrcTablesList("[RES_NAME]", "")%>.
    If you have more than one source it will list all you sources.
    However I can't see when you plan to refresh your variable. getSrcTablesList won't work before/after the interface execution.
    Regards,
    JeromeFr

  • How to populate table name dynamically to a ref cursor

    Hi,
    I came accross with a requirement that in ref cursor how can i pass the table name
    for ex
    open ref_cur for select * from emp;Like that i've some 100 tables , instead of typing each and every time the table name
    that should be dynamically changed
    Like below
    open ref_cur for select * from &tbl_nm;How can i do that??
    Thank you

    I assume you are using SQL*Plus:
    SQL> variable ref_cur refcursor;
    SQL> begin
      2      open :ref_cur for select * from &tbl_nm;
      3  end;
      4  /
    Enter value for tbl_nm: emp
    old   2:     open :ref_cur for select * from &tbl_nm;
    new   2:     open :ref_cur for select * from emp;
    PL/SQL procedure successfully completed.
    SQL> print ref_cur
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 12/17/1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 02/20/1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 02/22/1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 04/02/1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 09/28/1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 05/01/1981 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 06/09/1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 04/19/1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            11/17/1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 09/08/1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 05/23/1987 00:00:00       1100                    20
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7900 JAMES      CLERK           7698 12/03/1981 00:00:00        950                    30
          7902 FORD       ANALYST         7566 12/03/1981 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 01/23/1982 00:00:00       1300                    10
    14 rows selected.
    SQL> begin
      2      open :ref_cur for select * from &tbl_nm;
      3  end;
      4  /
    Enter value for tbl_nm: dept
    old   2:     open :ref_cur for select * from &tbl_nm;
    new   2:     open :ref_cur for select * from dept;
    PL/SQL procedure successfully completed.
    SQL> print ref_cur
        DEPTNO DNAME          LOC
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
    SQL> SY.

  • Getting problem when retriving Table name

    Hi,
    I'm having problem when i trying to get the table name from database. I'm using NetBeans 6.0, And It does n't show any error during compile and run time. I could n't find where the problem is?
    Code:_
    DatabaseMetaData dbm=conn.getMetaData();
    String[] types={"TABLES"};
    ResultSet rs=dbm.getTables("%","%","%",types);
    System.out.println("TableName:");
    while(rs.next())
    String tableName=rs.getString("TABLE_NAME");
    String tableSchema=rs.getString("TABLE_SCHEM");
    String tableCatalog=rs.getString("TABLE_CAT");
    System.out.println(tableName);
    conn.close();
    System.out.println("Disconnected from database");
    Output is:_
    MySQL Connect Example.
    TableName:
    BUILD SUCCESSFUL
    Regds,
    Prabu
    Edited by: [email protected] on Apr 16, 2008 12:32 PM

    Why did you repost? Don't do this, it is extremely rude!
    Stick with your other thread. I just gave you what I believe to be the correct answer.
    [Original Post|http://forum.java.sun.com/thread.jspa?threadID=5286520&tstart=0]

  • Can we pass IT table name dynamically to READ and SORT stmt

    Hello All,
      i have a requirement in which i am passing table name using a variable and want to read the same table: so my question is can we execute read and sort stmt with dynamic IT name. please see below for explaination.
    v_itname = <it_2>.
    now read using variable
    READ table ( v_itname ) with key <field>.
    and
    SORT ( v_itname ) by (otab).
    thanks
    Mani

    Hi ,
    This can be done. Please refer to the  codes below. Please note that the code will work if the itabs are of type standard table else it may dump.
    You just need to replace the variables form the values from your internal table.
    DATA: v_table1(10) TYPE c VALUE 'I_MARA',
          v_field(10)  TYPE c VALUE 'MATNR',
          i_mara TYPE STANDARD TABLE OF mara.
    FIELD-SYMBOLS : <fs_tab>   TYPE STANDARD TABLE,
                    <fs_field> TYPE ANY.
    DATA: otab TYPE abap_sortorder_tab,
    oline TYPE abap_sortorder.
    SELECT * UP TO 10 ROWS
      FROM  mara
      INTO TABLE i_mara.
    IF sy-subrc = 0.
      ASSIGN (v_table1) TO <fs_tab>.
      IF sy-subrc = 0.
        oline-name = v_field.
        APPEND oline TO otab.
        SORT <fs_tab> BY (otab).
        READ TABLE <fs_tab>
        WITH KEY (v_field) = '000000000020000989' "
        BINARY SEARCH
        TRANSPORTING NO FIELDS.
        IF sy-subrc = 0.
        ENDIF.
      ENDIF.
    ENDIF.
    Regards,
    Dev.

  • Problem in using animations in dynamic images

    Hi Friendz,
    I've problem in using effects or animation after calling
    images dynamically from outside the flash.
    If somebody have any solution for this, then please solve my
    problem immediately....

    Little more information about your problem would be helpfull.

  • How to use table name as variable in insert statement

    Hi,
    I want to insert data from the cursor into the table and I want to submit table name as a variable. I tried the code below but it's not working. Any ideas how to solve this problem? Thx
    DECLARE
    v_new_table_name VARCHAR2(30) := 'test';
    --open cursor   
    CURSOR ACM IS
    SELECT *
    FROM DWH.CLI_DIMENSION@SLSPDW CLI
    WHERE where_clause
    FROM some_table;
    BEGIN
    FOR REC_ACM IN ACM LOOP
    EXECUTE IMMEDIATE 'INSERT INTO ' || v_new_table_name || ' VALUES REC_ACM'; --table name as a variable in which the data from cursor will be inserted
    V_ROWCOUNT := V_ROWCOUNT + 1;
    IF MOD(V_ROWCOUNT, 100) = 0 THEN --this feature commits after 100 rows.
    COMMIT;
    END IF;
    END LOOP;
    COMMIT;
    DBMS_OUTPUT.PUT_LINE('Number of inserted records:' || V_ROWCOUNT);
    END;

    Try this and let me know if it works. I have not tested it so I can not say for sure.
    DECLARE
      v_new_table_name VARCHAR2(30) := 'test';
      CURSOR ACM IS
        SELECT * FROM DWH.CLI_DIMENSION@SLSPDW CLI
                WHERE where_clause
                FROM some_table;
      BEGIN
      loop
       fetch ACM INTO REC_ACM
       exit when ACM%NOTFOUND;
       EXECUTE IMMEDIATE 'INSERT INTO ' || v_new_table_name || ' VALUES REC_ACM';
       V_ROWCOUNT := V_ROWCOUNT + 1;
       IF MOD(V_ROWCOUNT, 100) = 0 THEN
        COMMIT;
       END IF;
      end loop;
      COMMIT;
      DBMS_OUTPUT.PUT_LINE('Number of inserted records:' || V_ROWCOUNT);
      END;

  • Use table name in UPDATE statement as variable

    Hi All,
    I am using ORACLE 9i AIX base. I want to write following procedure:
    PROCEDURE update_header (
    p_care_msg_nbr IN NUMBER,
    p_care_msg_id IN NUMBER,
    p_care_msg_gkey IN NUMBER,
    p_old_status IN VARCHAR2,
    p_new_status IN VARCHAR2
    IS
    l_table varchar2(50);
    BEGIN
    l_table := 'CARE_EDI_MESSAGES';
    UPDATE '&l_table'
    SET status = p_new_status,
    changed = sysdate,
    changer = user
    WHERE care_msg_no = p_care_msg_nbr
    AND care_msg_id = p_care_msg_id
    AND gkey = p_care_msg_gkey
    AND status = p_old_status;
    END;
    I want to give the table name by passing value in a variable or parameter. Is it the write way or can I do this function in any other way.
    Pleae tell me in urgency.
    Thanks & Regards
    Hassan Raza

    This implies that you have several tables with identical or near identical structures, otherwise you will get errors if any of the mentioned columns do not exist in the table passed but ...
    You cannot use a substitution variable that way. Oracle will ask for a value when you try to create the procedure, and compile what ever value you supply into the procedure viz.
    SQL> CREATE PROCEDURE p AS
      2  l_id NUMBER;
      3  BEGIN
      4     SELECT id INTO l_id FROM &t;
      5  END;
      6  /
    Enter value for t: T
    old   4:    SELECT id INTO l_id FROM &t;
    new   4:    SELECT id INTO l_id FROM T;
    Procedure created.
    SQL> SELECT text FROM user_source WHERE name = 'P'
      2  ORDER BY line;
    TEXT
    PROCEDURE p AS
    l_id NUMBER;
    BEGIN
       SELECT id INTO l_id FROM T;
    END;Even if that is the effect you want, note that there are no quotes around the substitution variable in the CREATE statement.
    If you want to be able to pass the name of the table to the procedure, then you need to make the table name a parameter, then build the sql statement and execute it using EXECUTE IMMEDIATE. Something more like:
    PROCEDURE update_header (p_care_msg_nbr  IN NUMBER,
                             p_care_msg_id   IN NUMBER,
                             p_care_msg_gkey IN NUMBER,
                             p_old_status    IN VARCHAR2,
                             p_new_status    IN VARCHAR2,
                             p_table         IN VARCHAR2) IS
    l_sqlstr VARCHAR2(4000);
    BEGIN
       l_sqlstr := 'UPDATE '||p_table||' SET status = :b1 '||
                   'changed = sysdate, changer = user '||
                   'WHERE care_msg_no = :b1 and care_msg_id = :b3 and '||
                   'gkey = :b4 and status = :b5';
       EXECUTE IMMEDIATE l_sqlstr
          USING p_new_status, p_care_msg_nbr, p_care_msg_id, p_care_msg_gkey, p_old_status;
    END;HTH
    John

  • To know schema using table name

    Can I know the schema using the table name.

    I have a handy if probably overcomplicated script for this:
    SQL> @which v$session
    Objects matching 'v$session':
    Name                                       Type                OWNER                Granted? Synonym
    V$SESSION                                  SYNONYM             PUBLIC
    SYS.V_$SESSION (VIEW)
    SQL> @which dual
    Objects matching 'dual':
    Name                                       Type                OWNER                Granted? Synonym
    DUAL                                       SYNONYM             PUBLIC
                                               TABLE               SYS                  Yes      DUAL
    SYS.DUAL (TABLE)
    www.williamrobertson.net/scripts/which.sql

Maybe you are looking for

  • Using DBCA 11g r2

    Hi, I installed 11g r2 and created database as well along with it. I wanted to use dbca to create another database but there is no "database configuration assistant" in "Configuration and migration tools" in program files. can someone tell as to why

  • Finder sidebar error 8058 when try to delete

    I have two old files in my finder sidebar that I can't delete . I am running in Lion. when I restart in 10.6.8 they are gone. but when I go back to Lion, they are still there and I cannot move them to trash. I get error code 8058 when I try to move t

  • Firefox constantly asks me to allow gmail chat.

    Everytime I sign into Gmail, firefox asks me if I'm sure I want to let the gmail chat plugin activate. I tell it yes and to remember, but it has no memory.

  • Might go for T400/500- Many questions concerning Think Vantage

    Hi, I am deciding on my first IBM, a T400 or T500 I have a few questions concerning the Think Vantage Function: a) Does the recovery DVD set back the hard drive partitions to factory settings? b) Does the Think Vantage function set back the hard driv

  • Time recording & transfer to cProjects

    Hi, I have successfully integrated cProjects and CATS. The CATS and cProjects are in different systems. The task that has been created in the cProjects gets reflected in the cat2 transaction against the employee who has been allocated the task in cPr