SQL Server - What is the best method to run the same query over multiple databases on multiple instances? for example we have many application databases, with the same schema that need to have information aggregated.
I currently use a script that relies on linked servers already being setup and a table that identifies which instance and database to loop through.
/* declare some cursor variables and the dynamic sql string variable */
DECLARE @currentDB nvarchar(64)
DECLARE @connectionstring nvarchar(256)
DECLARE @sqlstring nvarchar(max)
CREATE TABLE #TEMP1
(
currentDB varchar(32)
,field1 varchar(128)
,field2 smallint
,field3 datetime
)
/* Build and open the cursor */
DECLARE connectioncursor CURSOR FAST_FORWARD
FOR
SELECT currentDB, connectionstring
FROM [admin].dbo.DatabaseList
WHERE dbtype = 'PROD'
OPEN connectioncursor
FETCH NEXT FROM connectioncursor INTO @currentDB, @connectionstring
/* Start the loop through db list */
WHILE @@FETCH_STATUS = 0
BEGIN
/* Build and set the sql string */
SET @sqlstring =
'
select
''' + @currentDB + '''
,field1, field2, field3
from ' + @connectionstring + '.dbo.table1
'
/* Insert the results from the iteration and fetch the next db */
INSERT INTO #TEMP1 exec sp_executesql @sqlstring
FETCH NEXT FROM connectioncursor INTO @currentDB, @connectionstring
END
/* Kill the cursor */
CLOSE connectioncursor
DEALLOCATE connectioncursor
select * from #TEMP1 -- some output
Be gentle I'm a TSQL newbie!
1 Answer 1
There's lots of options.
- PowerShell
- SSMS's Multi Server Query Functionality
- Linked Servers
- Batch File with a loop and sqlcmd variables
-
1If I do use linked servers, is there anything flawed with just looping through each one and building the connection screen as above? I have been taught to fear cursors and dynamic SQL but this seems like one of those necessary evil situations.Alan Whited– Alan Whited2012年04月18日 20:14:38 +00:00Commented Apr 18, 2012 at 20:14
-
2Cursors and dSQL are fine for stuff like this as there's no other option. You are controlling the code so it shouldn't be a problem to push it out like this. You are dependent on the linked servers being setup correctly, but that's an acceptable risk in my book.mrdenny– mrdenny2012年04月18日 20:17:03 +00:00Commented Apr 18, 2012 at 20:17