Using a Variable for Table Name  with a cursor

Hello All
Is it possible to use a Parameter passed to a procedure as the table name
in a cursor selection statment. I thought the below would work but I get
a error. Does anyone have any ideas?? The Error is listed below to.
Here's the code I just complied
CREATE OR REPLACE PROCEDURE Dup_Add(NEWQATABLE IN VARCHAR2) IS
CURSOR c1 IS SELECT MUNI,PROV FROM NEWQATABLE GROUP BY MUNI, PROV;
c1rec c1%ROWTYPE;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO c1rec;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(c1rec.MUNI);
END LOOP;
CLOSE c1;
END;
Here is the errors
LINE/COL ERROR
3/8 PLS-00341: declaration of cursor 'C1' is incomplete or malformed
3/15 PL/SQL: SQL Statement ignored
3/38 PLS-00201: identifier 'NEWQATABLE' must be declared
5/7 PL/SQL: Item ignored
10/3 PL/SQL: SQL Statement ignored
10/17 PLS-00320: the declaration of the type of this expression is
incomplete or malformed
12/3 PL/SQL: Statement ignored
12/24 PLS-00320: the declaration of the type of this expression is
incomplete or malformed
LINE/COL ERROR
Thanks
Peter

If you are going to have a table name or a column name as a parameter, then you have to open the cursor dynamically. The following example uses Native Dynamic SQL (NDS) to open a ref cursor dynamically. I also eliminated the group by clause, since it is intended for use with aggregate functions and you weren't using an aggregate function. Also notice that there are some other differences in terms of defining variables and fetching and so forth.
SQL> CREATE TABLE test_table
  2  AS
  3  SELECT deptno AS muni,
  4         dname  AS prov
  5  FROM   dept
  6  /
Table created.
SQL> CREATE OR REPLACE PROCEDURE Dup_Add
  2    (newqatable IN VARCHAR2)
  3  IS
  4    TYPE cursor_type IS REF CURSOR;
  5    c1 cursor_type;
  6    c1muni NUMBER;
  7    c1prov VARCHAR2 (20);
  8  BEGIN
  9    OPEN c1 FOR 'SELECT muni, prov FROM ' || newqatable;
10    LOOP
11      FETCH c1 INTO c1muni, c1prov;
12      EXIT WHEN c1%NOTFOUND;
13      DBMS_OUTPUT.PUT_LINE (c1muni || ' ' || c1prov);
14    END LOOP;
15    CLOSE c1;
16  END;
17  /
Procedure created.
SQL> SHOW ERRORS
No errors.
SQL> SET SERVEROUTPUT ON
SQL> EXECUTE dup_add ('test_table')
10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS
PL/SQL procedure successfully completed.

Similar Messages

  • How to insert variable for table name in Select statement ?

    I am creating a stored procedure which will take two table names as IN parameters. Within the procedures I would like to use the parameters in the following manner;
         SELECT count(*)
         INTO v_target_cnt
         FROM TargetTable;
    TargetTable is one of the parameters passed in. When I do this however it does not recognize the parameter. I have tried assigning the parameter to a local variable and using the variable, with not luck.
    Any help....thanks

    Null,
    What you are describing is called a LEXICAL parameter, which is allowed (preceded by an ampersand) in sql but not in pl/sql because it would not be possible to compile it. That is why you need to use Andrew's suggestion to make the sql dynamic. In older versions you would need to use DBMS_SQL which is horrible and now thankfully redundant.

  • Querying the schema for table name with column value!

    In my schema i have 500+ tables and other objects.
    i have a column with the name BO_PRODUCT_CODE.
    I wants to know in what tables the value of BO_PRODUCT_CODE='FX03'.
    i have query the user_tab_columns which gives me the result with 90 tables having the column BO_PRODUCT_CODE.
    What is query which will give me the exact number/name of the table whose column value is FX03. ie, BO_PRODUCT_CODE='FX03'.

    Hi you can use this approach:
    BEGIN
    v_str VARCHAR2(250);
    v_count NUMBER :=0;
    DECLARE
    FOR loop_tbl IN ( SELECT DISTINCT table_name FROM USER_TAB_COLUMNS
    WHERE column_name ='BO_PRODUCT_CODE' )
    LOOP
    v_str := 'SELECT COUNT(*) FROM ' || loop_tbl.table_name || ' WHERE BO_PRODUCT_CODE=||'''' ||'FX03' || '''' '
    EXECUTE IMMEDIATE v_str INTO v_count ;
    IF v_count > 0 THEN
    DBMS_OUTPUT.PUT_LINE ('Table Name :'|| loop_tbl.table_name || ' Count :'||v_count);
    END IF;
    v_count :=0;
    END LOOP;
    EXCEPTION
    WHEN others THEN
    DBMS_OUTPUT.PUT_LINE(SQLERRM);
    END;
    Please remove if any syntax error.
    Regards

  • Urgent help needed in Using German Umlauts for Table names

    I created a table with Umlauts But i am not able to select from
    this table.I am also not able to drop this table as i get
    invalid character error.What setting has to be set.The NLS is I
    believe GERMAN_GERMANY.WE8ISO8859P1

    Pl do not post duplicate threads - insert dont work in Workflow
    Srini

  • How to use bind variable value for table name in select statement.

    Hi everyone,
    I am having tough time to use value of bind variable for table name in select statement. I tried &p37_table_name. ,
    :p37_table_name or v('p37_table_name) but none worked.
    Following is the sql for interactive report:
    select * from v('p37_table_name') where key_loc = :P37_KEY_LOC and
    to_char(inspection_dte,'mm/dd/yyyy') = :P37_INSP_DT AND :p37_column_name is not null ;
    I am setting value of p37_table_name in previous page which is atm_state_day_insp.
    Following is error msg:
    "Query cannot be parsed, please check the syntax of your query. (ORA-00933: SQL command not properly ended) "
    Any help would be higly appreciated.
    Raj

    Interestingly enough I always had the same impression that you had to use a function to do this but found out from someone else that all you need to do is change the radio button from Use Query-Specific Column Names and Validate Query to Use Generic Column Names (parse query at runtime only). Apex will substitute your bind variable for you at run-time (something you can't normally do in pl/sql without using dynamic sql)

  • Can substitution strings be used for table name references?

    Hi,
    I was wondering if it's possible to use substituion strings for table names in SQL queries. This would allow for me to edit all references to a table at one location. For instance, if a table name or dblink changed, I could edit the substitution string or application item to ensure all the queries reference the new table.
    For example:
    select * from &table1.
    table1 would be the substitution string for the actual table name
    I know this is possible if I used a pl/sql function returning a query, but I would much rather use a substition string in a SQL query.
    Thanks in advance.
    Brian

    i think not
    because how create the fields of * in this case
    in the other because all is dynamic, i think that you obtain only an error

  • Using variables as table names. Ideas for alternative designs

    Hi,
    I am designing an application which uses synonyms to pull information from 'client' DBs via DB Links. The synonyms are created with a DB_ID in the name (example: CUSTOMER_100, CUSTOMER_200... where 100 and 200 are DB IDs from 2 separate client DBs.
    I have a procedure which selects data from the synonym based on what DB_ID is passed to the procedure. I want to be able to run this one procedure for any DB_ID that is entered. I am now aware I cannot use variable names for table names and using EXECUTE IMMEDIATE doesnt seem to fit for what I am trying to do.
    Does anybody have any suggestions or re-design options I could use to achieve this generic procedure that will select from a certain synonym based on the DB info input parameters? Thanks.
    CREATE OR REPLACE PROCEDURE CUSTOMER_TEST(p_host IN VARCHAR2, p_db_name IN VARCHAR2, p_schema IN VARCHAR)
    IS
       v_hostname     VARCHAR2 (50) := UPPER (p_host);
       v_instance     VARCHAR2 (50) := UPPER (p_db_name);
       v_schema     VARCHAR2 (50) := UPPER (p_schema);
       v_db_id  NUMBER;  
       v_synonym VARCHAR2(50);
       CURSOR insert_customer
       IS
         SELECT 
           c.customer_fname,
           c.customer_lname
         FROM v_synonym_name c;
    BEGIN
    -- GET DB_ID BASED ON INPUT PARAMETERS       
      select d.db_id
      into v_db_id
      from  t_mv_db_accounts ac,
      t_mv_db_instances i,
       t_mv_dbs d,
       t_mv_hosts h
      where ac.db_ID = d.db_ID
      and i.db_ID = d.db_ID
      and i.HOST_ID = h.host_id
      and upper(H.HOST_NAME) = v_hostname
      and upper(D.DB_NAME) = v_instance
      and upper(Ac.ACCOUNT_NAME) = v_schema;
      --APPEND DB_ID TO THE SYNOYNM NAME
      v_synonym := 'CUSTOMER_'||v_db_id;
      FOR cust_rec IN insert_customer
      LOOP
         INSERT INTO CUSTOMER_RESULTS (First_Name, Last_Name)
         VALUES (cust_rec.customer_fname, cust_rec.customer_lname);
      END LOOP;
      COMMIT;
    END;
    Rgs,
    Rob

    Hi
    rules engine style with table that holds the logic or code SQL directly in the procedure and IF THEN ELSE with db_id. Latter is better because SQL is native and objects are checked every time procedure is compiled.
    James showed the simplest way but this rather complex way gives you more flexibility between instances if ever needed.
    CREATE TABLE synonym_dml(db_id number not null primary key, sql_text clob)
    INSERT INTO synonym_dml VALUES (100, 'INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer100')
    INSERT INTO synonym_dml VALUES (200, 'INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer200')
    set serveroutput on size unlimited
    create or replace
    PROCEDURE Execute_Synonym_Dml(p_host VARCHAR2, p_db_name VARCHAR2, p_schema VARCHAR) IS
    BEGIN
      FOR r IN (
        SELECT sql_text FROM synonym_dml
        --  WHERE db_id IN (
        --    SELECT d.db_id
        --    FROM t_mv_db_accounts ac, t_mv_db_instances i, t_mv_dbs d, t_mv_hosts h
        --    WHERE ac.db_id = d.db_id
        --      AND i.db_id = d.db_id
        --      AND i.host_id = h.host_id
        --      AND upper(h.host_name)      = p_hostname
        --      AND upper(d.db_name)        = p_instance
        --      AND upper(ac.account_name)  = p_schema
      LOOP
        DBMS_OUTPUT.PUT_LINE('-- executing immediately ' || r.sql_text);
        --EXECUTE IMMEDIATE r.sql_text;
      END LOOP;
    END;
    create or replace
    PROCEDURE Execute_Synonym_Dml_Too(p_host VARCHAR2, p_db_name VARCHAR2, p_schema VARCHAR) IS
      PROCEDURE DB_ID_100 IS
      BEGIN
        DBMS_OUTPUT.PUT_LINE('-- executing DB_ID_100');
        --INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer100;
      END;
      PROCEDURE DB_ID_200 IS
      BEGIN
        DBMS_OUTPUT.PUT_LINE('-- executing DB_ID_200');
        --INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer200;
      END;
    BEGIN
      FOR r IN (
        SELECT 100 db_id FROM dual
        --  SELECT d.db_id
        --  FROM t_mv_db_accounts ac, t_mv_db_instances i, t_mv_dbs d, t_mv_hosts h
        --  WHERE ac.db_id = d.db_id
        --    AND i.db_id = d.db_id
        --    AND i.host_id = h.host_id
        --    AND upper(h.host_name)      = p_hostname
        --    AND upper(d.db_name)        = p_instance
        --    AND upper(ac.account_name)  = p_schema
      LOOP
        IF (r.db_id = 100) THEN
          DB_ID_100;
        ELSIF (r.db_id = 200) THEN
          DB_ID_200;
        ELSE
          RAISE_APPLICATION_ERROR(-20001, 'Unknown DB_ID ' || r.db_id);
        END IF;
      END LOOP;
    END;
    EXECUTE Execute_Synonym_Dml('demo','demo','demo');
    EXECUTE Execute_Synonym_Dml_Too('demo','demo','demo');
    DROP TABLE synonym_dml PURGE
    DROP PROCEDURE Execute_Synonym_Dml
    table SYNONYM_DML created.
    1 rows inserted.
    1 rows inserted.
    PROCEDURE EXECUTE_SYNONYM_DML compiled
    PROCEDURE EXECUTE_SYNONYM_DML_TOO compiled
    anonymous block completed
    -- executing immediately INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer100
    -- executing immediately INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer200
    anonymous block completed
    -- executing DB_ID_100
    table SYNONYM_DML dropped.
    procedure EXECUTE_SYNONYM_DML dropped.

  • How to use simple types for table column names ?

    Hi,
    can any one tell how to to use simple types for table column names?
    It is required in internationalizing of webdynpro applications.
    Regards,
    Rajesh

    Hi,
    1: define required column names in <SimpleType>
    2:use the following code to get those values
    3:bind 'text' property of Column headers to context attributes
    4:take a context attribute 'Value' as type of <SimpleType>
    5:set these values to context attributes
    IWDAttributeInfo objAttrInfo=wdContext.getNodeInfo().getAttribute(IPrivate<ViewName>View.IContextElement.VALUE);
    ISimpleTypeModifiable simple=objAttrInfo.getModifiableSimpleType();
    Map m=simple.getEnumerationTexts();
    Collection c=m.values();
    Iterator it=c.iterator();
    if(it.hasNext())
    wdContext.currentContextElement.set<att1>(it.next().toString);
    if(it.hasNext())
    wdContext.currentContextElement.set<att2>(it.next().toString);
    if(it.hasNext())
    wdContext.currentContextElement.set<att3>(it.next().toString);
    Regards
    LakshmiNarayana

  • How can I use a variable for an interface log and error fle

    I want to use a variable for the interface's log and error file so that when I migrate from Dev to QA to Prod I don't have to do a lot of editing.
    Specifically on the "flow" tab for the "target", I want a variable to be the first part of the path for the log (\\sundev1\fnd1-hypd1) and join this with the rest (\update\log\logfile.log) within the LOG_FILE_NAME field.
    Thank you!

    Hi,
    It is quite simple....
    just use the <%=odiRef.getSchemaName("D")%> before the file name and configure both path in the topology linked to each context.

  • How to pass parameter for table name in  form6i.

    Hi ,
    I am facing the problem to pass parameter for table name in form6i.
    If any solution please infirm me earliest to my mail id.
    ([email protected])
    example:
    begin
    select ename into :ename
    from :tab_name
    where empno =7788;
    end;
    It gives error as bad bind variable 'tab_name'
    *** where :ename and :tab_name are form fields
    Thanking you,
    Balasaheb

    object name not taken as table --> what do u mean by
    this?
    Please be more clear..
    Regards
    PriyaI have two block. First block I am displaying all the table using user_objects table. Another block I want display, user which table selected, corresponding table all the records.

  • Create Unique Index On Flow does not work for table names 23 characters

    I have a "create unique index on flow table" step that is dynamically generated by the IKM.
    The index name that is generated by the IKM is based on the table name except that the created index name is prefixed with "I$_" and ends with "_idx". Obviously, since Oracle table names can not exceed 30 characters in length, the index creation step will fail if the base table name exceeds 23 characters.
    I have tried to substring the index name generation step in the IKM so that it only uses the first 23 characters of the table name, but have not had any luck with using the "substring" command together with snpRef.getTable call.
    This is the section of the IKM that I desire to change:
    - <Field name="Txt" type="java.lang.String">
    - <![CDATA[
    create unique index      <%=snpRef.getTable("L","INT_NAME","W")%>_idx
    on          <%=snpRef.getTable("L","INT_NAME","W")%> (<%=snpRef.getColList("", "[COL_NAME]", ", ", "", "UK")%>)
    <%=snpRef.getUserExit("FLOW_TABLE_OPTIONS")%>
    ]]>
    </Field>
    I would like to change the above to something similar to the following (note the only change is the addition of substring(1,23))
    - <Field name="Txt" type="java.lang.String">
    - <![CDATA[
    create unique index <%=snpRef.getTable("L","INT_NAME","W")*.substring(1,23)*%_idx
    on          <%=snpRef.getTable("L","INT_NAME","W")%> (<%=snpRef.getColList("", "[COL_NAME]", ", ", "", "UK")%>)
    <%=snpRef.getUserExit("FLOW_TABLE_OPTIONS")%>
    ]]>
    </Field>
    Any help greatly appreciated. Thanks.

    As the index is temporary, just like the I$ talbel, the easiest way is to replace the table name with some unique identifier like the session is:
    bq. I$_&lt;%=odiRef.getSession("SESS_NO")%&gt;_idx
    If for some reason that is not unique enough, add the NNO:
    bq. I$_&lt;%=odiRef.getSession("SESS_NO")%&gt;&lt;%=odiRef.getSession("NNO")%&gt; \\ _idx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to  use data function using characterstics variable for calculation on

    how to  use data function using characterstics variable for calculation on  attribute as key figure

    Hi Gayatri
    Did you not see my answer for CASE because CASE does indeed offer the use of the BETWEEN clause, but DECODE does not. Let me give you a little synopsis of DECODE.
    In its most simple form it takes 4 values and looks like this: DECODE(A, B, C, D)
    This essentially means, IF A = B THEN C ELSE D
    The trick to solving BETWEEN in a DECODE is to work out algoriths where A = B. Because we don't know how many values are between 00 and 99, although I could guess there were 100 we could of course have 100 parts in the DECODE but that would be awful. How about if we look at it another way and say this:
    IF PART_NUMBER < 'SDK00' THEN pay_amount
    ELSE IF PART_NUMBER > 'SDK99' THEN pay_AMOUNT
    ELSE pay_amount + 100
    This statement only had 2 hard coded values, but how to make DECODE work with less than? Easy, we use the LEAST function. The LEAST function takes 2 values and returns the one with the lowest value. So I use LEAST(PART_NUMBER, 'SDK00') then whenever the PART_NUMBER is lower than SDK00 it will be true. A similar situation exists for the opposite function GREATEST. Putting all of this together then, you can do this:
    DECODE(PART_NUMBER, GREATEST(PART_NUMBER, 'SDK00'), DECODE(PART_NUMBER, LEAST(PART_NUMBER, 'SDK99'), PAY_AMOUNT * 100, PAY_AMOUNT), PAY_AMOUNT)
    In English this can be read as follows:
    IF the PART_NUMBER is greater than or equal to SDK00 and the PART_NUMBER is less than or equal to SDK99 THEN PAY_AMOUNT x 100 ELSE 0
    Best wishes
    Michael

  • How to find the column name and table name with a value

    Hi All
    How to find the column name and table name with "Value".
    For Example i have value named "Srikkanth" This value will be stored in one table and in one column i we dont know the table how to find the table name and column name
    Any help is highly appricatable
    Thanks & Regards
    Srikkanth.M

    2 solutions by Michaels (the latter is 11g upwards only)...
    michaels>  var val varchar2(5)
    michaels>  exec :val := 'as'
    PL/SQL procedure successfully completed.
    michaels>  select distinct substr (:val, 1, 11) "Searchword",
                    substr (table_name, 1, 14) "Table",
                    substr (t.column_value.getstringval (), 1, 50) "Column/Value"
               from cols,
                    table
                       (xmlsequence
                           (dbms_xmlgen.getxmltype ('select ' || column_name
                                                    || ' from ' || table_name
                                                    || ' where upper('
                                                    || column_name
                                                    || ') like upper(''%' || :val
                                                    || '%'')'
                                                   ).extract ('ROWSET/ROW/*')
                       ) t
    --        where table_name in ('EMPLOYEES', 'JOB_HISTORY', 'DEPARTMENTS')
           order by "Table"or
    SQL> select table_name,
           column_name,
           :search_string search_string,
           result
      from cols,
           xmltable(('ora:view("'||table_name||'")/ROW/'||column_name||'[ora:contains(text(),"%'|| :search_string || '%") > 0]')
           columns result varchar2(10) path '.'
    where table_name in ('EMP', 'DEPT')
    TABLE_NAME           COLUMN_NAME          SEARCH_STRING        RESULT   
    DEPT                 DNAME                ES                   RESEARCH 
    DEPT                 DNAME                ES                   SALES    
    EMP                  ENAME                ES                   JONES    
    EMP                  ENAME                ES                   JAMES    
    EMP                  JOB                  ES                   SALESMAN 
    EMP                  JOB                  ES                   SALESMAN 
    EMP                  JOB                  ES                   SALESMAN 
    EMP                  JOB                  ES                   PRESIDENT
    EMP                  JOB                  ES                   SALESMAN 
    9 rows selected.

  • How to create a record for table PLAF with order type 'NB'.

    How to create a record for table PLAF with order type 'NB'(standard purchase order).
    who can tell me the T-code or some usefull information?
    Thanks.

    Hi
    This will be updated automatically when generate planned orders thru MRP. (MD02)
    regards
    Srinivas

  • Use a variable for the integer in Fmt offset modifier

    I'm trying to pluck values out of a long array of comma separated string
    values.
    I'm doing this within a loop and would like to use the loop interation to
    point to the starting point in the array.
    Here's what I have working so far:
    Fmt (scratch,"%s<%s[i0t44]",transmitBuf);
    Works great.
    Now if I go in and change i0 to i3 then my modifier doesn't start looking
    for a comma "," until after the 3rd character. Still working great. However....
    If I try to use an integer called "loop" instead of the literal offset
    value it blows up:
    Fmt (scratch,"%s<%s[iloopt44]",transmitBuf);
    Is there a way that I can use a variable for the integer portion of the
    offset modifer?
    Thanks All!

    Hi Roberto
    Thank you. I actually need to use a symbolic value for the interger section of the modifer vs. the specifier.
    So, in my example:
    Fmt (scratch,"%s<%s[i0t44]",transmitBuf); 
    I want to make the following substitution (Assume z=0)
    Fmt (scratch,"%s<%s[izt44]",transmitBuf);
    Some background...
    I'm looking to loop index through a long CSV string array (transmitBuf) that looks like this:
    1,PEEP,7,6,,,21,20,
    So on my first loop when I use the following:
    Fmt (scratch,"%s<%s[i0t44]",transmitBuf); 
    scratch = "1"
    ... Perfect. I now do a string length of scratch (which equals 1)
    and add 1 to it, I'm ready for my next loop which would
    literally read like this:
    Fmt (scratch,"%s<%s[i2t44]",transmitBuf); 
    However, I want to put this inside a loop, so I would like to
    increment a variable (++z) and use the following:
    Fmt (scratch,"%s<%s[izt44]",transmitBuf); ---- Ka-Boom!
    So it's the use of the variable in the modifer that blows up
    the Fmt command.
    appreciate any thoughts...
    Thanks
    Mark

Maybe you are looking for

  • Can't get WiFi to work on E1200

    My 1200 v 1.0 was working fine until I tried to link a wireless internet camera. Apparently I screwed something up in the setup such that I've lost my WiFi connection to my laptop and one wireless desktop. Fortunately my wired connection still works.

  • Transferring music from iPhone to MacBook Pro

    I  just bought a new macbook pro and went to transfer my music from my iPhone to the new iTunes, and only half transferred. The other half are in the iTunes music section but are not highlighted. Help?

  • Mega view 588

    have megaview 588 (which overall i LOVE) but am unable to get it to work with TV, either playing recorded shows TO tv or recording FROM TV - have correct cables, plugged in correctly but best i can get is audio only, no video... my TV has 2 input hoo

  • Color management issue: What am I doing wrong?

    Ok, the problem is pretty simple to explain; In Bridge CS5's "Creative Suite Color Settings..." I select "Europe Prepress 3" and hit apply. No problems thus far, it does set the same setting across InDesign, Photoshop and Illustrator. Looking at the

  • PC Sync Setting not working

    When I click on PC Sync Setting nothing happens (It does nothing). I uninstalled Nokia PC Suite over 3 times and installed the latest version 7.0.8.2 (PC Sync ) and nothing changed. Note: 1 - The phone is connected to the PC and in standby mode. 2 -