Business Need:
Database Links are used to connect from one database to a remote
database without exposing/repeating connection details to the end user.
Oracle DB 12g is used for these SQLs. But the SQLs will be
applicable most of the recent versions.
DB Link Creation:
Here is the command to create DB Link:
CREATE DATABASE LINK DBLINK_NAME
CONNECT TO REMOTE_SCHEMA IDENTIFIED BY REMOTE_PWD
USING 'REMOTE_TNSSTRING';
To use the DB Link, the REMOTE_TNSSTRING
needs to be defined in the DB Server’s TNSNAMES.ORA file, you are connecting
to. Otherwise this will give TNS Error.
DB Link Creation without TNS Definition:
Here is command to create DB Link to a remote database whose TNS
String is not defined in the server:
CREATE DATABASE LINK DBLINK_NAME
CONNECT TO
REMOTE_SCHEMA IDENTIFIED BY REMOTE_PWD
USING
'(DESCRIPTION=
(ADDRESS=(PROTOCOL=TCP)(HOST=<mymachine.mydomain.com>)(PORT=<1521>))
(CONNECT_DATA=(SERVICE_NAME=<service or sid name>))
)';
<mymachine.mydomain.com> à Domain Name or IP Address of
Remote Database
<1521> à Port Number of Remote Database
<service or sid name> à Service Name of Remote
Database
DB Link Usage:
Tables within DB Link can be accessed using the format <table
name> @ <DB Link name>, just like any local table (Eg: USERS@DEV).
If frequently used, create a local synonym:
CREATE SYNONYM RTUSERS FOR USERS@DBLINK_NAME;
So the below SQLs work in the same way:
SELECT * FROM USERS@DBLINK_NAME;
SELECT * FROM RTUSERS;
Other Notes/Considerations:
Few points to add before using
DB Links:
- Direct DB Links to Production might cause data security policy violation. Be careful over sensitive data exposure.
- Query Optimization is poor across DB Links. A few steps might help improve performance over DB Links:
- If a single table is accessed
frequently, use a local temp table and fill the required data in the local
table and use. DB Link to be used only in the first selection (to store data in
temp table)
- Use query-in-query format to
choose remote data, if possible
Eg: Only 1 order type will be present in remote table. Use “(SELECT COL1, COL2 FROM ORDERS WHERE ORDER_TYPE = 21) X” instead of Order Type in the
main query.
Keywords:
Oracle, DB Link, Database Link, Remote Database, TNSNAMES, Query,
SQL, SQLPLUS
No comments:
Post a Comment