While Loop to Iterate through Databases

后端 未结 7 1192
暖寄归人
暖寄归人 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:54

    This doesn't use a loop. Hope this helps!

    Note that "TABLE_OWNER" is that same as "SCHEMA Owner" and "TABLE_TYPE" will identify if the item is a table OR view.

    --This will return all tables, table owners and table types for all database(s) that are NOT 'Offline'
    --Offline database information will not appear
    
    Declare @temp_table table(
    DB_NAME varchar(max),
    TABLE_OWNER varchar(max),
    TABLE_NAME varchar(max),
    TABLE_TYPE varchar(max),
    REMARKS varchar(max)
    )
    
    INSERT INTO @temp_table (DB_NAME, TABLE_OWNER, TABLE_NAME, TABLE_TYPE,REMARKS)
    
    EXECUTE master.sys.sp_MSforeachdb 'USE [?]; EXEC sp_tables'
    
    SELECT DB_NAME, TABLE_OWNER, TABLE_NAME, TABLE_TYPE 
    FROM @temp_table 
    --Uncomment below if you are seaching for 1 database
    --WHERE DB_NAME = '<Enter specific DB Name>'
    
    --For all databases other than 'System Databases'
    WHERE DB_NAME not in ('master','model','msdn','tempdb')
    order by 1,2,3
    
    0 讨论(0)
提交回复
热议问题