同义词的所有者跟目标数据库对象的所有者通常是不一样的,也可以一样。当所有者不一样的时候,需要确保同义词的所有者有权限访问实际对象所有者对应的表。
CREATE SYNONYM 语句用来创建同义词,语法格式如下:
CREATE SYNONYM synonym_name FOR [owner.]object_name ;
示例:创建跨数据库所有者的同义词
创建单独的用户 tpcc_ro ,对用户 tpcc 赋权允许使用 grant 命令。
obclient> create user tpcc_ro identified by 123456;
Query OK, 0 rows affected (0.04 sec)
obclient> grant all privileges on tpcc_ro.* to tpcc_ro;
Query OK, 0 rows affected (0.02 sec)
obclient> grant create synonym on *.* to tpcc_ro ;
Query OK, 0 rows affected (0.02 sec)
obclient> grant select on sys.* to tpcc_ro ;
Query OK, 0 rows affected (0.01 sec)
obclient> grant all privileges on tpcc.* to tpcc with grant option;
Query OK, 0 rows affected (0.02 sec)
登录 tpcc 用户,授权用户 tpcc_ro 读取表 ordr 、ordl。
$obclient -h127.1 -utpcc@oracle0_85#obv22_stable -P2883 -p123456 tpcc
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
obclient> grant select on ordr to tpcc_ro;
Query OK, 0 rows affected (0.02 sec)
obclient> grant select on ordl to tpcc_ro;
Query OK, 0 rows affected (0.01 sec)
登录 tpcc_ro 用户,创建同义词。
obclient> create synonym ordr for tpcc.ordr;
Query OK, 0 rows affected (0.02 sec)
obclient> create synonym ordl for tpcc.ordl;
Query OK, 0 rows affected (0.01 sec)
obclient> select count(*) from ordr t1 join ordl t2 on (t1.o_w_id=t2.ol_w_id and t1.o_d_id=t2.ol_d_id and t1.o_id=t2.ol_o_id);
+----------+
| COUNT(*) |
+----------+
| 626 |
+----------+
1 row in set (0.02 sec)
obclient> select * from user_synonyms;
+--------------+-------------+------------+---------+
| SYNONYM_NAME | TABLE_OWNER | TABLE_NAME | DB_LINK |
+--------------+-------------+------------+---------+
| ORDR | TPCC | ORDR | NULL |
| ORDL | TPCC | ORDL | NULL |
| WARE | TPCC | WARE | NULL |
+--------------+-------------+------------+---------+
3 rows in set (0.02 sec)