There are two types of synonyms: public and private synonyms.
The owner of a private synonym is the creator of the synonym.
Example
The following example creates two users to demonstrate public and private synonyms.
Creating test users
A user with enough privileges to create users creates the two demonstration users and grants the necessary privileges to the users:
create user usr_syn_maker
identified by pw
default tablespace data
quota unlimited on data
temporary tablespace temp;
create user usr_syn_consumer
identified by pw
temporary tablespace temp;
grant
create session,
create synonym, create public synonym,
create table,
drop public synonym
to
usr_syn_maker;
grant
create session
to
usr_syn_consumer;
Objects of USR_SYN_MAKER
usr_syn_maker
creates two tables and a public and private synonym pointing to these tables:
connect usr_syn_maker/pw
create table tab_pub (txt varchar2(50));
create table tab_prv (txt varchar2(50));
grant select on tab_pub to usr_syn_consumer;
grant select on tab_prv to usr_syn_consumer;
create public synonym syn_pub for tab_pub;
create synonym syn_prv for tab_prv;
insert into tab_pub values('A public synonym points here');
insert into tab_prv values('A private synonym points here');
commit;
USR_SYN_CONSUMER
usr_syn_consumer
uses the synonyms to select from the tables:
connect usr_syn_consumer/pw
select * from syn_pub;
select * from syn_prv;
-- ORA-00942: table or view does not exist
select * from usr_syn_maker.syn_prv;
Using the synonyms in PL/SQL
In addition to using direct SQL,
usr_syn_consumer
now also creates a
PL/SQL procedure to select via the synonyms.
First, the privileged user needs to grant create procedure
to usr_syn_consumer`:
connect / as sysdba
grant create procedure to usr_syn_consumer;
Now, usr_syn_consumer
is ready to create the procedure:
connect usr_syn_consumer/pw
create procedure use_syn authid definer as begin
for pub in (select txt from syn_pub) loop
dbms_output.put_line(pub.txt);
end loop;
for prv in (select txt from usr_syn_maker.syn_prv) loop
dbms_output.put_line(prv.txt);
end loop;
end use_syn;
/
begin
use_syn;
end;
/
Privileges
A public synonym can be dropped by anyone who has the dop public synonym
system privilege, regardless of who created the synonym.
There is a drop public synonym
, but no drop synonym
system privilege.