-1

I have two databases and a UDL connection string to each one. I'd like to construct a query that joins tables from both databases.

I'm doing a query from a single database like this.

string query = "...";

using (OleDbConnection connection = new OleDbConnection(ConnectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
{
    int count = command.ExecuteNonQuery();
}

Can someone show me an example of doing the same thing with a query that joins tables from two databases?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

2 Answers2

1

So, the thing that was throwing me off was the assumption I'd need two connection strings. There doesn't appear to be any way to construct a single query in ADO.NET that involves two connections.

In my case, both databases are on the same server. So only one connection string is required. Then, the query can include database prefixes to identify which database you are referring to.

SELECT [DB1].[dbo].Field1, [DB2].[dbo].Field2 FROM ...
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

You can select both in two DataTables and then join them using Linq.

var results = from par in dt1.AsEnumerable()
                join chi in dt2.AsEnumerable()
                  on (int)par["ID"] equals (int)chi["ParentID"]
                select new //Here you can leave it that way or use your own object.
                           // select new MyResultObject(){prop1 = x, prop2 = y ...}
                {
                    ParentID = (int)par["ParentID"],
                    ChildID = (int)par["ChildID"],
                    ColA = (string)par["ColA"],
                    ColB = (int)par["ColB"],
                    ColC = (double)chi["ColC"],
                    ColD = (date)chi["ColD"]
                };

Hope it helps :)

Cleber Machado
  • 196
  • 3
  • 6