Using Oracle database links without unreadable dynamic SQL

情到浓时终转凉″ 提交于 2019-12-07 08:54:58

问题


How can I write a neat PL/SQL stored procedure that can execute against a given database link?

It gets really messy, writing stuff like this:

   PROCEDURE my_proc(aDbLink IN VARCHAR2)
   IS
   BEGIN       
       EXECUTE IMMEDIATE '
       SELECT mycolumn, anothercolumn
       FROM MYTABLE@' || aDbLink || '
       WHERE such-and-such...'
   END

as the query gets bigger.

What else might I do? I'm stuck using stored procedures, and expect that my procedures will execute against one of several db links.


回答1:


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;



回答2:


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


来源:https://stackoverflow.com/questions/6209155/using-oracle-database-links-without-unreadable-dynamic-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!