Hi Ahmed,
I add a new answer to demonstrate another method suggested by jva. All the tables must share a common structure (so that Oracle will be able to know the datatype of the columns of the view at compile time).
Setup:
-- create 2 schemas
CREATE USER u1 IDENTIFIED BY u1;
CREATE USER u2 IDENTIFIED BY u2;
GRANT RESOURCE TO u1;
GRANT RESOURCE TO u2;
-- one table in each schema
CREATE TABLE u1.t AS
SELECT 2 * ROWNUM ID, 'foo' DATA FROM dual CONNECT BY LEVEL <= 5;
CREATE TABLE u2.t AS
SELECT 2 * ROWNUM - 1 ID, 'bar' DATA FROM dual CONNECT BY LEVEL <= 5;
GRANT SELECT ON u2.t TO u1;
-- the common structure
CREATE TYPE u1.t_row AS OBJECT (ID NUMBER, DATA VARCHAR2(3));
/
CREATE TYPE u1.t_row_list AS TABLE OF u1.t_row;
/
CREATE OR REPLACE PACKAGE u1.test_pck IS
schema_name VARCHAR2(30) := 'U1';
FUNCTION select_t RETURN u1.t_row_list PIPELINED;
END test_pck;
/
--Definition of the pipelined function and the view:
CREATE OR REPLACE PACKAGE BODY u1.test_pck IS
FUNCTION select_t RETURN u1.t_row_list PIPELINED IS
l_rc SYS_REFCURSOR;
l_id NUMBER;
l_data VARCHAR2(3);
BEGIN
OPEN l_rc FOR 'SELECT id, data
FROM ' || dbms_assert.schema_name(schema_name) || '.t';
LOOP
FETCH l_rc
INTO l_id, l_data;
EXIT WHEN l_rc%NOTFOUND;
PIPE ROW (u1.t_row(l_id, l_data));
END LOOP;
CLOSE l_rc;
END select_t;
END test_pck;
/
CREATE OR REPLACE VIEW u1.v AS
SELECT ID, DATA
FROM TABLE(u1.test_pck.select_t);
You would then define the global variable in the package containing the schema name and then query the view:
SQL> EXEC u1.test_pck.schema_name := 'U1';
PL/SQL procedure successfully completed
SQL> SELECT * FROM u1.v;
ID DATA
---------- ----
2 foo
4 foo
6 foo
8 foo
10 foo
SQL> EXEC u1.test_pck.schema_name := 'U2';
PL/SQL procedure successfully completed
SQL> SELECT * FROM u1.v;
ID DATA
---------- ----
1 bar
3 bar
5 bar
7 bar
9 bar