SQL:统计并显示一个scheme下所有表的所有行和列

SQL: count and show all rows and columns of all tables under a scheme

网上某处(来源丢失,可能在这里)我得到了这个SQL-声明:

SELECT t.NAME AS TableName, SUM(a.total_pages) * 8 AS TotalSpaceKB, p.Rows FROM sys.tables t 
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id 
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id 
LEFT OUTER JOIN sys.schemas s ON t.schema_id = s.schema_id 
WHERE t.NAME NOT LIKE 'dt%' AND t.NAME LIKE '%MY_TABLES%' AND s.Name LIKE 'MY_ACHEMA'
  AND t.is_ms_shipped = 0
  AND i.OBJECT_ID > 255
GROUP BY t.Name, p.Rows
ORDER BY p.Rows DESC

这让我看到了 3 列的美丽景色。像这样:

           TableName  TotalSpaceKB     Rows
               TABLE       3231656    76000
               TABLE       2305632    29136
               TABLE       2213128    14160
               TABLE       1954200     3020
etc...

现在我想扩展它以包括每个 table 的列数。如何做到这一点?

添加 INFORMATION_SCHEMA.COLUMNS.

应该对您有用
SELECT t.NAME AS TableName, SUM(a.total_pages) * 8 AS TotalSpaceKB, p.Rows, COUNT(COLUMN_NAME) AS ColumnCount
FROM sys.tables t 
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id 
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id 
LEFT JOIN sys.schemas s ON t.schema_id = s.schema_id 
LEFT JOIN INFORMATION_SCHEMA.COLUMNS ISC ON t.NAME = ISC.TABLE_NAME 
WHERE t.NAME NOT LIKE 'dt%' AND t.NAME LIKE '%MY_TABLES%' AND s.Name LIKE 'MY_ACHEMA'
  AND t.is_ms_shipped = 0
  AND i.OBJECT_ID > 255
GROUP BY t.Name, p.Rows
ORDER BY p.Rows DESC

我删除了分组并使用了子查询:

SELECT
    t.NAME AS TableName,
    (SELECT SUM(a.total_pages) * 8 
        FROM sys.indexes i
        INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 
        INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id 
        WHERE t.OBJECT_ID = i.object_id AND i.OBJECT_ID > 255
    ) AS TotalSpaceKB,
    (SELECT SUM(p.Rows)
        FROM sys.indexes i
        INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 
        WHERE t.OBJECT_ID = i.object_id AND i.OBJECT_ID > 255
    ) AS Rows,
    (SELECT COUNT(*) FROM sys.columns c WHERE t.OBJECT_ID = c.object_id) AS Columns
FROM sys.tables t 
LEFT OUTER JOIN sys.schemas s ON t.schema_id = s.schema_id 
WHERE t.NAME NOT LIKE 'dt%' AND t.NAME LIKE '%MY_TABLES%' AND s.Name LIKE 'MY_ACHEMA'
  AND t.is_ms_shipped = 0
ORDER BY Rows DESC