SMSS中是否有办法检测表是否有任何记录?我需要获取有记录的表列表。也许有一个sql语句可以解决这个问题吗?
答案 0 :(得分:23)
试试这个 - 给你表名和行数:
SELECT
t.NAME AS TableName,
SUM(p.rows) AS [RowCount]
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
WHERE
i.index_id <= 1
GROUP BY
t.NAME, i.object_id, i.index_id, i.name
ORDER BY
SUM(p.rows) DESC
它在单个输出中显示所有表及其行数。
答案 1 :(得分:14)
答案 2 :(得分:8)
更简单的语法:
SELECT [Name] = o.name
, [RowCount] = SUM(p.row_count)
FROM SYS.DM_DB_PARTITION_STATS p
INNER JOIN
SYS.TABLES o
ON p.[object_ID] = o.[object_id]
WHERE index_id <= 1 -- Heap or clustered index only
GROUP BY o.name
ORDER BY 2 desc
答案 3 :(得分:3)
您可以使用此存储过程:
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
这将返回数据库中每个表的结果集(每个表都显示名称,行数以及其他信息)。
以下是如何将它们放入表变量中,并按行数排序:
DECLARE @TBL TABLE (
[name] nvarchar(500),
[rows] bigint,
[reserved] nvarchar(500),
[data] nvarchar(500),
[index_size] nvarchar(500),
[unused] nvarchar(500)
)
INSERT INTO @TBL
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
SELECT * FROM @TBL
ORDER BY [rows] DESC
答案 4 :(得分:0)
希望,它可以帮助您-
SELECT name AS [TableList] FROM SYS.DM_DB_PARTITION_STATS s
INNER JOIN sys.tables t ON t.[object_id] = s.[object_id]
WHERE row_count = 0
此代码显示该表列表,其中不包含任何数据或行。
谢谢!