While Loop to Iterate through Databases

后端 未结 7 1270
暖寄归人
暖寄归人 2021-02-05 13:05

I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns. this is was I have done

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 13:53

    I ended up writing one last week on the fly for some stuff I was doing.

    Blog post here:

    http://tsells.wordpress.com/2012/02/14/sql-server-database-iterator/

    Here is the code.

    SET NOCOUNT ON
    GO
    use master
    go
    
    Declare
    @dbname nvarchar(500),
    @variable1 int,
    @variable2 int,
    @variable3 int,
    @totaldb int = 0,
    @totaldbonserver int = 0,
    @totaldbwithmatches int = 0
    
    -- Get non system databases
    Declare mycursor CURSOR for select name, database_id from SYS.databases where database_id > 4 order by name desc
    
    open mycursor
    
    fetch next from mycursor into @dbname, @variable1
    
    while (@@FETCH_STATUS <> -1)
        BEGIN
            DECLARE @ParmDefinition NVARCHAR(500)
            Declare @mysql nvarchar(500) = 'select @variable2OUT = COUNT(*) from [' + @dbname + '].INFORMATION_SCHEMA.TABLES where Upper(TABLE_NAME) like ''MyTable''';
            SET @ParmDefinition = N'@variable2OUT int OUTPUT'
            set @totaldbonserver = @totaldbonserver + 1
            Execute sp_executesql @mysql, @ParmDefinition, @variable2 OUTPUT            
    
            if @variable2 = 1
            BEGIN
                DECLARE @ParmDefinition2 NVARCHAR(500)
                Declare @mysql2 nvarchar(500) = 'select @variable2OUT = COUNT(*) from [' + @dbname + '].dbo.MyTable';
                SET @ParmDefinition2 = N'@variable2OUT int OUTPUT'
                Execute sp_executesql @mysql2, @ParmDefinition2, @variable3 OUTPUT
                set @totaldb = @totaldb + 1
    
                if @variable3 > 1
                BEGIN
                    Print @dbname + ' matched the criteria'
                    set @totaldbwithmatches = @totaldbwithmatches + 1
                END
                ELSE
                Select 1
            END    
    
            fetch next from mycursor into @dbname, @variable1
        END
        PRINT 'Total databases on server: '
        Print @totaldbonserver
    
        PRINT 'Total databases tested () : '
        Print @totaldb
    
        PRINT 'Total databases with matches: '
        Print @totaldbwithmatches
    CLOSE mycursor
    DEALLOCATE mycursor
    

提交回复
热议问题