Search code examples
oracle-databaseplsqloracle12c

PL/SQL - function parameter as table name - how is this possible?


When working with Oracle (using 12c Enterprise Edition Release 12.1.0.2.0), we can write something like ...

SQL> select * from dual ;
DUMMY  
X  

However, it is not possible to use 'a' in the FROM clause, as a table, as it were - eg

SQL> select * from 'a' ;

Error starting at line : 1 in command -
select * from 'a'
Error at Command Line : 1 Column : 15
Error report -
SQL Error: ORA-00903: invalid table name
00903. 00000 -  "invalid table name"
*Cause:    
*Action:

When coding a CURSOR FOR LOOP (PL/SQL) I found that the following function code compiled:

create or replace function f (
  a varchar2
) return varchar2
is
begin
  for r in ( select * from a )  -- parameter (type varchar2) as table name!
  loop
    dbms_output.put_line( ' a -> ' || a  ) ;
  end loop;
  return a ;
end f ;
/

Function F compiled

Testing

set serveroutput on

SQL> select f( 'z' ) from dual ;
F('Z')  
z       


a -> z
 a -> z

Questions

{1} How is it possible that can we use a parameter name (that represents a single varchar2) in the FROM clause of a SELECT statement in a PL/SQL cursor for loop?

{2} (In the example) Why is DBMS_OUTPUT.PUT_LINE() apparently executed twice?


Solution

  • If you take this line

    for r in ( select * from a ) -- parameter (type varchar2) as table name!

    Then Oracle dose not select from varchar2 variable a - it selects from table a which by coincidence has the same name as your variable.