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

后端 未结 16 1223
轮回少年
轮回少年 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:44

    I think the common approach is to SELECT * FROM INFORMATION_SCHEMA.TABLES for each database using sp_MSforeachdb

    I created a snippet in VS Code that I think it might be helpful.

    Query

    IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;
    SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;
    TRUNCATE TABLE #alltables;
    EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';
    SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%%';
    GO 
    

    Snippet

    {
        "List all tables": {
            "prefix": "sqlListTable",
            "body": [
                "IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;",
                "SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;",
                "TRUNCATE TABLE #alltables;",
                "EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';",
                "SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%$0%';",
                "GO"
            ]
        }
    }
    

提交回复
热议问题