Loop through multiple Linked servers in Query

  • 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 query is doing. Also, from a reporting standpoint, building the initial 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!

  • You can do this through SSMS, using Registered Servers:

    http://msdn.microsoft.com/en-us/library/bb964743(v=sql.105).aspx

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply