开发者

SQL Server Script to Iterate through servers Part 2

I am trying to create a script to obtain data from a multiple databases in a server and then I want it to continue to the next server and do the same. I already created a script to work with one server and all its databases. The script is the same for all databases, tables in all the servers.

My question, is how do I have the script recognize the linked servers that I linked to my current server and continue to obtain data from those servers? Is there a hidden stored procedure or command that someone may know? I basically want to runs the below script through all my servers. When its done iterating through all the databases in one server, I want it to continue to the next server and do the same. I'm going to be saving all the data in a table.

Here is my script below, I want to have the script run through 5 servers which I currently have linked to one of my servers:

   SET NOCOUNT ON DECLARE @DBNAME NVARCHAR(MAX) DECLARE @DBNAME1 NVARCHAR(MAX) DECLARE @varSQL NVARCHAR(MAX)


DROP TABLE TEMPIMGCOUNTERSERVER3 CREATE TABLE TEMPIMGCOUNTERSERVER3 (DBname NVARCHAR(MAX), Images INT, FileSize INT, DBCreation DATETIME)

DECLARE DBNAME CURSOR FAST_FORWARD FOR select name from sys.databases where [NAME] LIKE 'Z%' AND create_date between '2011-02-06' and '2011-02-12' ORDER BY [create_date]

OPEN DBNAME

FETCH NEXT FROM DBNAME INTO @DBname WHILE (@@FETCH_STATUS=0) BEGIN

Set @varSQL='INSERT INTO TEMPIMGCOUNTERSERVER3 (DBNAME, IMAGES, FileSize, DBCreation) 
SELECT ''['+@DBNAME+']'', SUM(PGCOUNT), sum(filesize/1024/1024), sys.databases.CREATE_DATE
    FROM SYS.DATABASES, ['+@DBNAME+'].dbo.tbldoc WHERE created between ''2011-02-06'' and ''2011-02-12''
    and sys.databases.name='''+@DBNAME+''' 
    GROUP BY sys.databases.NAME, sys.databases.CREATE_DATE' 
EXEC SP_EXECUTESQL @varSQL

FETCH NEXT FROM DBNAME 
INTO @DBNAME
END

CLOSE DBNAME
DEALLOCATE DBNAME

INSERT TEMPIMGCOUNTERSERVER3 (DBNAME, IMAGES, FILESIZE)  
SELECT @@SERVERNAME + ' ' +'TOTAL IMAGES AND FILE SIZE', SUM(IMAGES), SUM(FILESIZE) FROM TEMPIMGCOUNTERSERVER3 

 SELECT DBNAME, IMAGES, FILESIZE, convert(VARCH开发者_运维技巧AR(10), 
DBCREATION, 101) AS DBCREATION FROM TEMPIMGCOUNTERSERVER3
GROUP BY DBNAME, IMAGES, FILESIZE, convert(VARCHAR(10), DBCREATION, 101)
HAVING SUM(IMAGES) is not null
ORDER BY DBCREATION

Should I add another cursor? Something with this script:

select srvname from master..sysservers where srvname like 'sql%'


i would just nest your cursor in another cursor that runs on the linked servers. filter the list of servers from master..sysservers on the srvproduct field where it equals "SQL Server". if there's anything is that list you don't want put it in a not in clause. then, modify your inner cursor to add the server name to the query, giving you a four part table name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜