How do I list all tables in all databases in SQL Server in a single result set?

后端 未结 16 1217
轮回少年
轮回少年 2020-11-28 07:36

I am looking for T-SQL code to list all tables in all databases in SQL Server (at least in SS2005 and SS2008; would be nice to also apply to SS2000). The catch, however, is

16条回答
  •  孤独总比滥情好
    2020-11-28 07:48

    Link to a stored-procedure-less approach that Bart Gawrych posted on Dataedo site

    I was asking myself, 'Do we really have to use a stored procedure here?' and I found this helpful post. (The state=0 was added to fix issues with offline databases per feedback from users of the linked page.)

    declare @sql nvarchar(max);
    
    select @sql = 
        (select ' UNION ALL
            SELECT ' +  + quotename(name,'''') + ' as database_name,
                   s.name COLLATE DATABASE_DEFAULT
                        AS schema_name,
                   t.name COLLATE DATABASE_DEFAULT as table_name 
                   FROM '+ quotename(name) + '.sys.tables t
                   JOIN '+ quotename(name) + '.sys.schemas s
                        on s.schema_id = t.schema_id'
        from sys.databases 
        where state=0
        order by [name] for xml path(''), type).value('.', 'nvarchar(max)');
    
    set @sql = stuff(@sql, 1, 12, '') + ' order by database_name, 
                                                   schema_name,
                                                   table_name';
    
    execute (@sql);
    

提交回复
热议问题