Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Loop through multiple Linked servers in Query
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

1 Posts

Posted - 11/12/2012 :  16:05:51  Show Profile  Reply with Quote
I have a challenge.

One of my jobs is to produce reports on data found in 7 different databases (and database servers). These databases are all linked on a single database server. The databases are identical in structure but they contain different data. In my queries, I perform a union (or union all) to merge all of the data into the same result set. The basic query does this:

Select % from LinkSvr1.DBNameA.dbo.Table1
Select % From LinkSvr2.DBNameB.dbo.Table1
etc..... all the way to LinkSvr6.

Sometimes my queries can become very complex and I find that once I nail my query down, I need to copy and paste my criteria into each section and change the Linked Server and DB name. The queries run fine but they are very hard to read, especially for someone else to interpret.

My thinking was that there must be an easy way to create a single query that loops through each linked server and returns all of the linked server data into a single result set. This way I write my query once and anyone else can easily see what the quesry is doing. Also, from a reporting standpoint, building the initia query would be very simple.

Is there some function, variable, code or stored proceedure that would help me perform this task?

I was thinking that I could save the Linked Server's DB information in a variable or stored proceedure (something) and then call on a loop to query each linked server.

Any ideas?

I know that was wordy but I've never done what I'm trying to ask. Hopefully someone understood me.

Thank you. Any and all suggestions are welcome!

Premature Yak Congratulator

22864 Posts

Posted - 11/17/2012 :  03:34:58  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
The below will generate SELECT query for each server. Copy the ouput and do modifications

select 'select * from '+name+'.dbname.table1' from sys.servers


Failing to plan is Planning to fail
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000