SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

Tb0n3
Starting Member

USA
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
Union
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!

madhivanan
Premature Yak Congratulator

India
22772 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


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
  Previous Topic Topic Next Topic  
 New 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.06 seconds. Powered By: Snitz Forums 2000