Using Oracle database links without unreadable dynamic SQL

▼魔方 西西 提交于 2019-12-05 17:31:00

The simplest way to avoid using dynamic SQL would be to create synonyms.

CREATE OR REPLACE SYNONYM MyTableRemote
   FOR MyTable@database_link

Your stored procedures would then simply refer to the synonym MyTableRemote. You could then have a separate method that took the database link name as a parameter and changed all the synonyms to point at the database link.

PROCEDURE replace_synonyms( p_db_link IN VARCHAR2 )
AS
BEGIN
  -- Adjust the query to identify all the synonyms that you want to recreate
  FOR syn IN (SELECT *
                FROM user_synonyms
               WHERE db_link IS NOT NULL)
  LOOP
    EXECUTE IMMEDIATE 
      'CREATE OR REPLACE SYNONYM ' || syn.synonym_name ||
      '   FOR ' || syn.table_owner || '.' || syn.table_name || '@' || p_db_link;
  END LOOP;
END;

If you don't want to use the synonym idea, you could try this method - use REPLACE and your own syntax to generate the SQL - I find this method makes debugging dynamic SQL a breeze:

PROCEDURE my_proc(aDbLink IN VARCHAR2)
IS
BEGIN       
    EXECUTE IMMEDIATE REPLACE('
    SELECT mycolumn, anothercolumn
    FROM MYTABLE@#DBLINK#
    WHERE such-and-such...'
       ,'#DBLINK#', aDbLink);
END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!