Joining tables from different servers

el ninho picture el ninho · Jan 6, 2012 · Viewed 84.8k times · Source

Any suggestions how to join tables from different servers in stored procedure?

Answer

scott.korin picture scott.korin · Jan 6, 2012

Without more details, it's hard to give direct examples, but here is the basic idea:

First, outside of the stored procedure, the host server (the server the stored procedure will be on) has to know about the second server, including (possibly) login information.

On your main server, run the sp_addlinkedserver stored procedure. This only has to be done once:

exec sp_addlinkedserver @server='(your second server)';

If you need to provide login information to this second server (for example, the process can't log in with the same credentials that are used in the initial database connection), do so with the sp_addlinkedsrvlogin stored proc:

exec sp_addlinkedsrvlogin @rmtsrvname='(your second server)',
@useself=false, 
@rmtuser='yourusername', 
@rmtpassword='yourpassword';

Then, in your stored procedure, you can specify tables on the second server:

SELECT table1.*
FROM table1
INNER JOIN [secondserver].[database].[schema].[table] AS table2 ON
    table1.joinfield = table2.joinfield