UNION with 2 DATABASES, SQL

Asked

Viewed 753 times

0

I need to integrate 2 TABLES from DBdifferent in one DGV.

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

Follow an ex. of how 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 I can connect two Databases in a SELECT UNION ?

  • Just put the database name before the table name. Assuming the database is called A, then just use A.table1. The rest of the select is normal. Is sql server?

  • @Mauritosanches: What is DGV?

  • @Josédiz Datagridview

  • @Mauritosanches: All right.

2 answers

1

  1. You should check if the user you are using on your connection has read permission in the other database.
  2. In the SELECT shall 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 it is necessary to put the user before the name of the database for example:

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

The Rest to do the UNION, WHERE And ETC, you just reference normally.

1

As long as the user has permission in both banks.

Assuming it is SQL-Server and the tables are equal in both databases:

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 equal 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 .....
  • Perfect! I am in SQL-Server yes, but still giving error. Probably because the user is not allowed to access the other database. They are hosted in the same account, but they are different users and passwords, if you have any hint of how I set up this permission, it would certainly solve my problem.

  • 1

    USE Adventureworks2012; GRANT SELECT ON sys.sql_logins TO Sylvester1; GRANT VIEW SERVER STATE to Sylvester1; GO

Browser other questions tagged

You are not signed in. Login or sign up in order to post.