Sunday, February 19, 2012

cross-database query from ASP.NET

How do you write a SQL SELECT statement for a cross-database query in ASP.NET (ADO.NET). I understand the server.database.owner.table structure, but the command runs under a connection. How do I run a query under two connections?You don't need 2 connections. Are your 2 databases on the same server?

If they are on the same server, the syntax would be like this:


SELECT
D1.column1,
D2.column2
FROM
database1.dbo.Table1 D1
INNER JOIN
database2.dbo.Table2 D2 ON D1.ID = D2.ForeignKey

If they are on different servers, the syntax would be like this:


SELECT
D1.column1,
D2.column2
FROM
Server1.database1.dbo.Table1 D1
INNER JOIN
Server2.database2.dbo.Table2 D2 ON D1.ID = D2.ForeignKey

You might encounter this error:Could not find server 'Server2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers. which means that the system stored procedure sp_addlinkedserver would need to be run to allow access to Server2 from Server1. SeeSQL Server Link Server Performance Tips for some information pertaining to linked servers.

Terri

No comments:

Post a Comment