简体   繁体   中英

Oracle SQL: create procedure that takes a table as input

I would like to create a procedure that takes a table (T in the example) as an input. However I don't want to provide the table name as a char and do something 'dynamic' like

begin
    execute immediate ('delete from '||T||' where ...');
end;

because the actual task I am dealing with involves several inputs to the function and a long query to execute which has a lot of apices... the string to execute becomes really messy and difficult to debug. I would like to have something simple as the following (which works):

CREATE or replace PROCEDURE fun (x NUMBER) AS
   BEGIN
      DELETE FROM MyTable WHERE MyTable.var= fun.x;
   END;
/

However giving the table as an input to the procedure (I need to do it because otherwise, in the real task, I would need to change the "T" in a lot of occurrences within the procedure) does not work:

CREATE or replace PROCEDURE fun (x NUMBER, T table) AS
   BEGIN
      DELETE FROM T WHERE T.var= fun.x;
   END;
/

Errors for PROCEDURE FUN
----------------------------
L:1 C:32       PLS-00103: Encountered the symbol "TABLE" when expecting one of the following:
                  in out <an identifier> <a double-quoted delimited-identifier>
                  ... long double ref char time timestamp interval date binary
                  national character nchar
               The symbol "<an identifier> was inserted before "TABLE" to continue.
1 statement failed.

Is it possible to have something close to what I want?

I have devised a tornaround which is surely not elegant but, according to the comments, appears to be the only way to avoid large pieces of dynamic "execute immediate" code.

CREATE or replace PROCEDURE fun (T_in char, T_out char, x number) 
as
   BEGIN

    /* I create a temporary replica with a view */
   execute immediate 'create or replace view tempview as select * from '||T_in;

    /* DO STUFF, for example: */
   delete from tempview where ente_segn = fun.x;

    /* Save the results in a new table */
   execute immediate 'create or replace view '||T_out||'  as select * from tempview';

   END;
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM