同义词的所有者跟目标数据库对象的所有者通常是不一样的,也可以一样。当所有者不一样的时候,需要确保同义词的所有者有权限访问实际对象所有者对应的表。

    CREATE SYNONYM 语句用来创建同义词,语法格式如下:

    1. CREATE SYNONYM synonym_name FOR [owner.]object_name ;

    示例:创建跨数据库所有者的同义词

    创建单独的用户 tpcc_ro ,对用户 tpcc 赋权允许使用 grant 命令。

    1. obclient> create user tpcc_ro identified by 123456;
    2. Query OK, 0 rows affected (0.04 sec)
    3. obclient> grant all privileges on tpcc_ro.* to tpcc_ro;
    4. Query OK, 0 rows affected (0.02 sec)
    5. obclient> grant create synonym on *.* to tpcc_ro ;
    6. Query OK, 0 rows affected (0.02 sec)
    7. obclient> grant select on sys.* to tpcc_ro ;
    8. Query OK, 0 rows affected (0.01 sec)
    9. obclient> grant all privileges on tpcc.* to tpcc with grant option;
    10. Query OK, 0 rows affected (0.02 sec)

    登录 tpcc 用户,授权用户 tpcc_ro 读取表 ordr 、ordl。

    1. $obclient -h127.1 -utpcc@oracle0_85#obv22_stable -P2883 -p123456 tpcc
    2. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    3. obclient> grant select on ordr to tpcc_ro;
    4. Query OK, 0 rows affected (0.02 sec)
    5. obclient> grant select on ordl to tpcc_ro;
    6. Query OK, 0 rows affected (0.01 sec)

    登录 tpcc_ro 用户,创建同义词。

    1. obclient> create synonym ordr for tpcc.ordr;
    2. Query OK, 0 rows affected (0.02 sec)
    3. obclient> create synonym ordl for tpcc.ordl;
    4. Query OK, 0 rows affected (0.01 sec)
    5. 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);
    6. +----------+
    7. | COUNT(*) |
    8. +----------+
    9. | 626 |
    10. +----------+
    11. 1 row in set (0.02 sec)
    12. obclient> select * from user_synonyms;
    13. +--------------+-------------+------------+---------+
    14. | SYNONYM_NAME | TABLE_OWNER | TABLE_NAME | DB_LINK |
    15. +--------------+-------------+------------+---------+
    16. | ORDR | TPCC | ORDR | NULL |
    17. | ORDL | TPCC | ORDL | NULL |
    18. | WARE | TPCC | WARE | NULL |
    19. +--------------+-------------+------------+---------+
    20. 3 rows in set (0.02 sec)