0

I've two databases with the same schema, I need to select data from two tables having same schema (same name, same column) using DATABASE LINK in Oracle ?

SQL> select * from TEST1;

        ID NAME
---------- ----------
         2 Two
         4 Foor

SQL> select * from TEST1@link22;

        ID NAME
---------- ----------
         1 One
         3 Three

SQL> select * from TEST1, TEST1@link22;
select * from TEST1, TEST1@link22
       *
ERROR at line 1:
ORA-00918: column ambiguously defined

I want to get the following result:

        ID NAME
---------- ----------
         2 Two
         4 Foor
         1 One
         3 Three

Regards,

1 Answer 1

3

Use UNION ALL operator

select * from TEST1
UNION ALL
select * from TEST1@link22;

EDIT:

Added function draft:

CREATE OR REPLACE TYPE site IS OBJECT (id NUMBER, name VARCHAR2(255));
/

CREATE OR REPLACE TYPE site_collection IS TABLE OF site;
/

CREATE OR REPLACE FUNCTION merge_sites (sites SYS.ODCIVARCHAR2LIST) RETURN site_collection PIPELINED
IS
    commandText VARCHAR2(4000);
    c SYS_REFCURSOR;
    sid test.id%type;
    sname test.name%type;
BEGIN
    FOR i IN 1..sites.COUNT LOOP
        commandText := 'SELECT id, name FROM ' || sites(i);
        OPEN c FOR commandText;

        LOOP
            FETCH c INTO sid, sname;
            EXIT WHEN c%NOTFOUND;           
            PIPE ROW (site(sid, sname));
        END LOOP;
    END LOOP;
END;
/

SELECT * FROM TABLE(merge_sites(sys.ODCIVARCHAR2LIST('test1', 'TEST1@link22')));

You need to secure the data types match between type and tables.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there another solution than using UNION ALL. As we can't use N union for N sites.
What's wrong with UNION ALL? Anything else will be more complex. This operator serves exactly to the purpose, to concatenate two row sources into one.
Let's say we have 100 sites, each one has the same schema (same situation I asked for), should I write 100 select queries, and use UNION ALL ?
If you want to have all rows from all the sites in one output, yes. If you have list of sites somewhere or the sites are added/removed over time you can use PL/SQL to build dynamic SQL and hide it behind PIPELINED function.
@BoubakrNOUR - Why would you be trying to write a query to read data from 100 different databases? The pipelined table function mostly works but it's not going to be very efficient and if 1 of the 100 databases is down or unreachable, it's going to die. It sounds like you really want to implement real multi-master replication between instances rather than coding this manually.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.