passing table name as parameter in oracle stored procedure

10.1k Views Asked by At

How to pass a table name as a parameter to a stored that runs an update statement on that table in oracle

2

There are 2 best solutions below

1
On

Do not allow users to enter random table names or you will find that they are changing data you did not expect - at the very least you need to whitelist which tables you are expecting them to pass in:

PROCEDURE updateTables(
  table_name VARCHAR2,
  value1     VARCHAR2,
  value2     VARHCAR2,
  value3     VARCHAR2
)
IS
BEGIN
  IF table_name = 'table1' THEN
    UPDATE table1
    SET    col1 = value1
    WHERE  col2 = value2;
  ELSIF table_name = 'table2' THEN
    UPDATE table2
    SET    col1 = value1,
           col3 = value2
    WHERE  col2 = value3;
  ELSIF table_name = 'table3' THEN
    UPDATE table3
    SET    col1 = value3,
           col2 = value1,
           col3 = value2
    WHERE  col1 = value3;
  ELSE
    RAISE_APPLICATION_ERROR( -20001, 'Invalid Table Name' );
  END IF;
END;
/
3
On

You will need to use Dynamic sql for this something like....

PROCEDURE UPDATE_My_Table
  (
      pTableName IN USER_TABLES.table_name%type,
      Param1 IN NVARCHAR2,
      Param2 IN NUMBER,
      Param3 IN NVARCHAR2
  )
  IS
  BEGIN
      execute immediate 
          'UPDATE '||pTableName
          ||' SET Column1 = :1, Column2 = :2'
          ||' WHERE Column3 = :3'
      using Param1 , Param2 , Param3;
  END;