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

Similar Messages

  • Variable as table name in update statement

    Hi everyone,
    I am trying to update a table whose name is based on bind variables in the form and is unknown until runtime. However, I haven't been able to find a way to do this. I'm currently trying the FORMS_DDL built-in, but no success here either. Has anyone ever done this?
    DECLARE
    matrix_temp_table VARCHAR2(50);
    BEGIN
    matrix_temp_table := 'TEMP_'||:mgmt_matrix_master.div_idkey||'_'||TO_CHAR(:mgmt_matrix_master.dept_idkey);
    FORMS_DDL('UPDATE '||matrix_temp_table||' SET create_date = :mgmt_matrix_master.create_date');
    END;

    You're right, issuing the statement using the table name itself only works outside of FORMS_DDL. After trudging through the documentation it seems the best way to accomplish what I am trying to do is by using the EXEC_SQL package. But, once again, I cant get this to work either. It seems to me what I am trying to do is a fairly simple thing, but apparently not. I'm now trying to use this code, but the table still isn't being updated.
    PROCEDURE update_matrix_temp_table IS
    matrix_temp_table VARCHAR2(50);
    update_connid EXEC_SQL.ConnType;
    update_cursor EXEC_SQL.CursType;
    ignore PLS_INTEGER;
    BEGIN
    matrix_temp_table := 'TEMP_'||:mgmt_matrix_master.div_idkey;
    update_connid := EXEC_SQL.CURR_CONNECTION;
    update_cursor := EXEC_SQL.OPEN_CURSOR(update_connid);
    EXEC_SQL.PARSE(update_connid, update_cursor, 'UPDATE '||matrix_temp_table||' SET emp_no = '||:mgmt_matrix_master.emp_no);
    ignore := EXEC_SQL.EXECUTE(update_connid, update_cursor);
    EXEC_SQL.PARSE(update_connid, update_cursor, 'COMMIT');
    ignore := EXEC_SQL.EXECUTE(update_connid, update_cursor);
    EXEC_SQL.CLOSE_CURSOR(update_cursor);
    EXCEPTION
         WHEN EXEC_SQL.PACKAGE_ERROR THEN
         IF EXEC_SQL.LAST_ERROR_CODE(update_connid) != 0 THEN
              Message('ERROR (source: ' ||TO_CHAR(EXEC_SQL.LAST_ERROR_CODE(update_connid))|| '): ' ||EXEC_SQL.LAST_ERROR_MESG(update_connid));
         END IF;
    END;

  • 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 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)

  • 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

  • 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

  • Can I use a select and update statement in a single jsp file?

    I want to update the BUY table everytime I would add a SELL transaction.....I want to minus the stocks that I sold to those that Ive bought before.....
    note: I used a seperate table in BUY and SELL transaction
    After I Have added a transaction, I want to update the buy table. This is my problem, can I used both SELECT and UPDATE statement at the same time in a single jsp file for example like this:
    select * from test, test1;
    update test
    set total_shares=total_shares-Stotal;
    where stock_code=Scode AND name_broker=Sbroker;
    Can i have both of these statements in the same jsp file in oder to update the buy table?
    Or can anyone suggest how can process that update?THANKS!
    --------------------

    Can i have both of these statements in the same jsp file in oder to update the buy table?Yes. But wouldn't it have been easier just to try it?

  • 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

  • Standard Program Name for updating the System-Variables everyday in BACKGRO

    Hi All,
    Can anybody tell me the Standard Program Name for updating the System-Variables everyday in BACKGROUND job?

    Hello matt,
    I have a program with variant.
    This VARIANT input values will store in TVARVC table every day night background job.
    i want the program name

  • 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

  • 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;

  • How user variable table names in select statement

    Dear all,
    I have three table gp1,gp2,g3. i want user variable table in sql query
    for example at oracle forms have a list table showing table names gp1,gp2,gp3
    at form i want user this query
    select gpno from :table where gpno=120;
    how i can specify table name Dynamicly in select query
    Thanks

    Forms_DDL is a one-way street: You can only pass DDL commands TO the database; you cannot get data back using Forms_DDL.
    Exec_SQL is the Forms package that enables dynamic sql within a form. But to retrieve data, you have to make a Exec_SQL call for every column in every row. So it is not a good thing to use, either.
    The ref cursor method should work. You could also retrieve the data into a record group using populate_group_with_query -- it also enables dynamic data retrieval.
    But if you already know you have three distinct tables and you know their names, I would keep it simple and just write three sql select statements.

  • 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.

  • How to use escape character in update statement.

    Hi All,
    I'm trying to update table using following sql update statement, but everytime it's asking me for the input due to the '&' value in below sql.
    UPDATE xyz_xyz
       SET NAME = 'ABC & PQR'
    WHERE ID = (SELECT ID
                   FROM abc_abc
                  WHERE NAME = 'C & PQR');Please let me know how to use escape character syntax or let me know if there is any alternative solution.
    Thanks,
    Vishwas

    Hi,
    By default, & marks a substitution variable name.
    If you're not using substitution variables in that statement (or, if this is in PL/SQL, in that entire package or procedure) then the easiest thing to do is just diable substitution variables; then & will be a normal character:
    SELECT  DEFINE  OFF
    UPDATE xyz_xyz
       SET NAME = 'ABC & PQR'
    WHERE ID = (SELECT ID
                   FROM abc_abc
                  WHERE NAME = 'C & PQR');
    SET  DEFINE  ONIf you can't do that, then & is always taken literally if it comes right before a single-quote, so you could say:
    UPDATE xyz_xyz
       SET NAME = 'ABC &' || ' PQR'
    WHERE ID = (SELECT ID
                   FROM abc_abc
                  WHERE NAME = 'C &' || ' PQR');There is a SQL*Plus "SET ESCAPE" command, too, but if you use it, you have to worry about whether the escape character is to be taken literally or not.
    SET   ESCAPE  \Yet another alternative is to make some other character, such as ~, mark the substitution variables:
    SET  DEFINE  ~Read all about them in the SQL*Plus manual.
    http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch2.htm#sthref103

  • Using Escape character in UPDATE statement

    SELECT REPLACE
              ( REPLACE
                     ( REPLACE( REPLACE( REPLACE( REPLACE( BODY, '<STARTOFLINK>' )
                                                , '<ENDOFLINK>' )
      FROM ARTICLEI need to use the above in an UPDATE statement to remove some HTML tags from a CLOB column. However when I run the script it asks for the substitution variables for the '&' characters. I've tried "ESCAPE '\'" but I think you can only use that with a like operand.
    Any suggestions?
    Message was edited by:
    Terrible
    As you can see the HTML tags have been converted in this post!! I'm trying to remove:
    & amp;
    & quot;
    & ndash;
    & #039;

    This may help;
    SQL> create table t (col1 varchar2(200))
    Table created.
    SQL> insert into t values('<STARTOFLINK>')
    PL/SQL executed.
    SQL> insert into t values('<ENDOFLINK>')
    PL/SQL executed.
    SQL> insert into t values(chr(38) || 'amp;')
    PL/SQL executed.
    SQL> insert into t values(chr(38) || 'quot;')
    PL/SQL executed.
    SQL> insert into t values(chr(38) || 'ndash;')
    PL/SQL executed.
    SQL> insert into t values(chr(38) || '#039;')
    PL/SQL executed.
    SQL> insert into t values('<STARTOFLINK>link<ENDOFLINK> '
                       || '  AMP:' || chr(38) || 'amp;'
                       || '  DQT:' || chr(38) || 'quot;'
                       || '  DASH:'|| chr(38) || 'ndash;'
                       || '  SQT:' || chr(38) || '#039;')
    PL/SQL executed.
    SQL> select * from t
    col1                                                                           
    <STARTOFLINK>                                                                  
    <ENDOFLINK>                                                                    
    <STARTOFLINK>link<ENDOFLINK>   AMP:&  DQT:"  DASH:–  SQT:' 
    7 rows selected.
    SQL> select regexp_replace(
              regexp_replace(
                 regexp_replace(
                    regexp_replace(
                       regexp_replace(col1, '<.*OFLINK>',NULL),
                    chr(38) || 'amp;', chr(38)),
                 chr(38) || 'quot;', chr(34)),
              chr(38) || 'ndash;', chr(45)),
           chr(38) || '#039;', chr(39))
    new_col from t
    NEW_COL                                                                        
       AMP:&  DQT:"  DASH:-  SQT:'                                                 
    7 rows selected.Message was edited by:
    MScallion
    The SELECT * values were not as they are displayed due to HTML conversions.

Maybe you are looking for

  • Dust specks under iPad mini screen

    My uncle from the US ordered an iPad mini online for me during launch day. It arrived Nov 2 when I was in the US and I have been using it ever since. I currently reside in the Philippines and then dust is really bothering me. What are my replacement

  • New Iphone for Partner

    Hi all, Just looking for some opinions please. My partner has a Samsung soul phone which she hates, and she likes the idea of an iphone, as I have had one for a year now and rave about it constantly. She has a laptop, and loves music, so uses itunes

  • Lousy web "Save Image" quality? And best res for others?

    Double header here. iTouch 2nd Gen: 1) When I "Save Image" from the web via the iTouch, it looks like total crap when opened in the device's photo library. Blurry. 2) When working with photos on my desktop, is there an optimum size/resolution I shoul

  • WAD : Changing Web Item Property

    Hi I have a requirement to change the Web item Info Field in WAD 7.0 (earlier Text Element in BW 3.5). Presentlt there are two property that is Width in Pixel & Height in Pixel i want to have Width in Pixel , Full Width , Height in Pixel & Full Heigh

  • VirtualProvider with Function Module

    Hi,Experts Can anyone tell me how to create a VirtualProvider with Function Module? I have read the How to guide"How to Implement a VirtualProvider with service",but I can't go throw the source code. Please give me a sample test code of yours! Thanks