同义词不起作用:USER.SYNONYM_NAME有效,但SYNONYM_NAME没有

时间:2016-07-28 08:02:28

标签: oracle stored-procedures synonym

我有以下问题:

我为用户创建了一个同义词,以便从另一个模式调用一个过程,这是all_synonyms表的输出,以USER_1的形式登录sqlplus:

OWNER   SYNONYM_NAME  TABLE_OWNER   TABLE_NAME      DB_LINK    ORIGIN_CON_ID
~~~~~   ~~~~~~~~~~~~  ~~~~~~~~~~~   ~~~~~~~~~~      ~~~~~~~    ~~~~~~~~~~~~~
USER_1  SYN_NAME      ADMIN         PROCEDURE_NAME  NULL       0

但是我无法仅使用同义词名称来运行它。如果我这样做,我会得到一个OORA-06550。例如:

exec SYN_NAME;
OORA-06550: line 1, column 7: PLS-00201: identifier 'SYN_NAME' must be declared

exec USER_1.SYN_NAME; //works as expected

我已经在SYN_NAME上执行`grant execute to USER_1;

还有什么我需要设置的吗?我不确定我错过了什么。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

如果我正确阅读了此程序,则架构管理员中存在该过程,您希望user_1能够调用它。

作为管理员用户:

grant execute on <procedure_name> to user_1;

as user_1:

create synonym <procedure_name> for admin.<procedure_name>;

答案 1 :(得分:1)

如果您更改current_schema,则可以看到该效果。如果它与您的用户匹配,那么它可以正常工作:

select user, sys_context( 'userenv', 'current_schema') as schema from dual;

USER                           SCHEMA                       
------------------------------ ------------------------------
USER_1                         USER_1                        

create synonym syn_name for admin.procedure_name;

Synonym SYN_NAME created.

exec syn_name;

PL/SQL procedure successfully completed.

但如果我的会话有不同的current_schema,那么同义词必须以我的真实用户名为前缀:

alter session set current_schema = user_2;

Session altered.

select user, sys_context( 'userenv', 'current_schema') as schema from dual;

USER                           SCHEMA                       
------------------------------ ------------------------------
USER_1                         USER_2                        

select owner, synonym_name, table_owner, table_name
from all_synonyms where synonym_name = 'SYN_NAME';

OWNER                          SYNONYM_NAME                   TABLE_OWNER                    TABLE_NAME                   
------------------------------ ------------------------------ ------------------------------ ------------------------------
USER_1                         SYN_NAME                       ADMIN                          PROCEDURE_NAME                

exec syn_name;

ORA-06550: line 1, column 7:
PLS-00201: identifier 'SYN_NAME' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

exec user_1.syn_name;

PL/SQL procedure successfully completed.

您可能不知道您正在更改当前架构;它可能发生在登录触发器中,可能是为了避免使用同义词。您可以使用以下方法检查当前架构:

select sys_context( 'userenv', 'current_schema') as schema from dual;

如果它实际上显示了ADMIN,那么您根本不需要同义词,只需直接调用PROCEDURE_NAME,必须在其前面添加ADMIN架构名称。