Question

I'm writing a program in C# using Visual Studio 2010.

I need to collect data from two tables which are in two different database. I'm using Microsoft SQL Server Management Studio to view the data.

Both database are on the same server. I wrote a SQL query to join multiple tables in the two databases and have no issue. I was able to look in the Management Studio to make sure that my query is correct.

When I was trying to put the query into my C# code, I realized the issue. I can only specify one database in the connection string.

var connectionSting = "Data Source=myTestServer.con;Initial Catalog=MyTrunkDB;MultipleActiveResultSets=True; User ID=User1;Password=somePW";

Say I need query data from the two database MyTrunkDB and MyBranchBD, how would I go about doing so? Assuming my query is correct and the only issue I have is to connect to two different database in one query.

I also found the someone suggest using something called store procedure, but I don't know anything about store procedure and couldn't find any related sample code.

If there's a way to do it in the C# code that would be great, since I know C# better.

Thanks!

Était-ce utile?

La solution

If you are simply querying the databases and not attempting to perform any kind of extensive logic, you can create a view within SQL Server that connects to both databases as outlined here --> Create view across multiple databases. You would then need to query the view with either raw ADO.NET or through LINQ to Entities and Entity Framework. If you need to do anything more complex, you will want to look into stored procedures.

**As T.S. pointed out, you will need to create this view on one of the two databases and make sure your connection string points to that database.

Autres conseils

Just name database and owner of the table before table name. In MS SQL Server this should work:

select top 100 *
from database.owner.table t1
join database.owner.table t2 on t1.field1=t2.flield1 

Also you could skip owner, it will substitute it with default:

select top 100 *
from database..table t1
join database..table t2 on t1.field1=t2.flield1

If you are writing this on C# and know it better than T-SQL you don't really need stored procedures, because you can substitute them with C# methods. I hope this helped.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top