SQL Server – Querying Two Databases with One Connection

authenticationsql serverwindows-authentication

I have a local database, DB1, that I created and is connected to my web application. My web application takes in stored procedures from DB1 and queries them. My application connects to SQL Server using my Windows Authentication account.

I have access to another database, DB2, on a different server that I have read only access to using the same windows account. Can I still query from DB2 if my application is only connected to DB1?

When I execute stored procedures in DB1 that also query stuff from DB2 it works on SQL Server Management Studio but I get an error when I try to do it on my application.

Best Answer

You need to add DB2 as a linked server on your DB1 instance. Once created, then you can specify [LinkedServer].[Database].[schema].[Table] to query the objects on that server. Other than linked servers, there is no other way for a connection to discover and connect to another server(even if you have access) for security reasons. If you create a linked server, you are specifying a connection that server DB1 can establish and query DB2, all from BD1, not from the client.

Hope that helps. How to create a linked server in MSSQL