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

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Loop through multiple Linked servers in Query

Author  Topic 

Tb0n3
Starting Member

1 Post

Posted - 2012-11-12 : 16:05:51
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

22864 Posts

Posted - 2012-11-17 : 03:34:58
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
   

- Advertisement -