Any suggestions how to join tables from different servers in stored procedure?
There are 2 steps to join tables from different servers. The first step is to link the SQL Servers. The next and the last step is to join the tables using the select query having the server name as prefix for the table name.
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully qualify table names.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With