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.
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
来源:https://stackoverflow.com/questions/6209155/using-oracle-database-links-without-unreadable-dynamic-sql