我有一个案例需要引用另一个数据库用户。我在引用数据库用户名时会硬编码。
SELECT * FROM eg001t3.DUAL; // example.
有没有办法动态地或基于数据库设置从视图中引用该db用户(eg001t3)?
答案 0 :(得分:3)
在pl / sql中,您可以使用EXECUTE IMMEDIATE或DBMS_SQL来动态引用对象。
以EXECUTE IMMEDIATE为例:
SQL> VARIABLE dyn_user VARCHAR2(30);
SQL> EXEC :dyn_user := 'SYS';
PL/SQL procedure successfully completed
dyn_user
---------
SYS
SQL> DECLARE
2 ln NUMBER;
3 BEGIN
4 EXECUTE IMMEDIATE 'SELECT 1
5 FROM ' || dbms_assert.schema_name(:dyn_user)
6 || '.DUAL'
7 INTO ln;
8 dbms_output.put_line(ln);
9 END;
10 /
1
PL/SQL procedure successfully completed
您还可以使用动态构建的REF CURSOR:
SQL> DECLARE
2 lc SYS_REFCURSOR;
3 ln NUMBER;
4 BEGIN
5 OPEN lc FOR 'SELECT 1
6 FROM ' || dbms_assert.schema_name(:dyn_user) || '.DUAL
7 CONNECT BY level <= 2';
8 LOOP
9 FETCH lc
10 INTO ln;
11 EXIT WHEN lc%NOTFOUND;
12 dbms_output.put_line(ln);
13 END LOOP;
14 CLOSE lc;
15 END;
16 /
1
1
如图所示,您可以使用DBMS_ASSERT验证您的输入。
答案 1 :(得分:2)
我添加了一个新答案来演示jva建议的其他方法。所有表必须共享一个公共结构(以便Oracle能够在编译时知道视图列的数据类型)。
设定:
-- 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);
然后,您将在包含模式名称的包中定义全局变量,然后查询视图:
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
答案 2 :(得分:1)
可能有更优雅的选项,但您可以动态创建同义词或使用动态SQL / EXECUTE IMMEDIATE。
答案 3 :(得分:1)
可能对您有用的另一个选项(取决于您需要执行此操作的应用程序环境)是暂时将您的命名空间更改为感兴趣的架构:
set current_schema不会以任何方式绕过Oracle权限模型 - 您仍然需要在其他模式的感兴趣的表上至少使用SELECT。