Posted - 11/12/2012 : 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
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.
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!