UNION with 2 DATABASES, SQL

0

I need to integrate 2 TABLES from DB different into a same DGV .

I found several tutorials, but none that helped me from configuration to the connection, at least not the way I work with the connections.

Follow an ex. of what I call a Select:

MySqlConnection conexaoSLT = ClassConexao.DBEMG();

MySqlCommand _comando = new MySqlCommand(String.Format("SELECT * FROM tabel1 WHERE Carro = @tipoCarro"), conexaoSLT );

MySqlDataReader _reader = _comando.ExecuteReader();
_reader.Read();

....

How can I connect two databases to a SELECT UNION ?

    
asked by anonymous 26.04.2017 / 15:37

2 answers

1
  • You should verify that the user you are using on your connection has read permission in the other database.
  • No SELECT should use the name of the other bank before the table reference.
  • Example:

    SELECT C.NOMCLI, C.CODCLI, E.CODCLI FROM DB1.CLIENTES C, DB2.CLIENTES E  
    

    It may happen that in your databases you need to put the user before the name of the bank for example:

    SELECT C.NOMCLI, C.CODCLI, E.CODCLI FROM USUARIO1.DB1.CLIENTES C, USUARIO 2.DB2.CLIENTES E  
    

    Rest to make UNION , WHERE E ETC, you only reference normally.

        
    26.04.2017 / 16:04
    1

    As long as the user has permission on both banks.

    Assuming it is SQL Server and the tables are the same on both banks:

    SELECT * FROM OUTRO_BANCO..TABELA WHERE ..... 
    UNION
    SELECT * FROM ESSE_BANCO..TABELA WHERE .....
    

    If the tables are different:

    SELECT campo1, campo2, campo3 FROM OUTRO_BANCO..TABELA WHERE ..... 
    UNION
    SELECT campo1, campo2, campo3 FROM ESSE_BANCO..TABELA WHERE .....
    

    If it's Oracle and the same tables:

    SELECT * FROM OUTRO_BANCO.TABELA WHERE ..... 
    UNION
    SELECT * FROM ESSE_BANCO.TABELA WHERE .....
    

    Oracle and different tables:

     SELECT campo1, campo2, campo3 FROM OUTRO_BANCO.TABELA WHERE ..... 
     UNION
     SELECT campo1, campo2, campo3 FROM ESSE_BANCO.TABELA WHERE .....
    
        
    26.04.2017 / 16:10