在SQL Server 2008中,如何获取表列表的行计数?
我有一个数据库,我希望获得以' BB'
开头的所有表格的行数我尝试了多种变体:
CREATE TABLE #RowCounts(NumberOfRows BIGINT, TableName VARCHAR(128))
EXEC sp_MSforeachtable 'INSERT INTO #RowCounts
SELECT COUNT_BIG(*) AS NumberOfRows,
''?'' AS TableName FROM ?'
SELECT TableName, NumberOfRows
FROM #RowCounts
ORDER BY NumberOfRows DESC, TableName
DROP TABLE #RowCounts
投掷''?'' AS TableName FROM ? WHERE ? LIKE 'BB%'
等内容
和''?'' AS TableName FROM ? WHERE ''?'' LIKE 'BB%'
我确信必须有办法做到这一点。如果您可以获取所有表的行数,那么应该能够为某些表获取它...对吗?
答案 0 :(得分:1)
尝试使用sys.dm_db_partition_stats DMV ..
$(":checkbox").change(function() {
var dataset3 = dataset.filter(function(el) {
var checkboxes = document.getElementsByName('result');
var index = 0;
var found = false;
while (index < checkboxes.length && !found) {
if (checkboxes[index].checked && el[0] == checkboxes[index].value) found=true;
++index;
}
return found;
});
document.getElementById("demo3").innerHTML = dataset3;
});
当您有大量插入,删除和立即检查计数时,这可能不够准确(偏差很小)..
如果您一直在使用sp_msforeach ..
select
object_name(object_id) as tablename,sum(row_count) as totalrows
from sys.dm_db_partition_stats
where object_name(object_id) like 'Bb%'--gives tables count which start with bb*
group by object_id
<强>参考文献:强>
How to fetch the row count for all tables in a SQL SERVER database
答案 1 :(得分:0)
如果数据库包含堆或集群索引表,那么我将使用以下方法之一:
SELECT s.name as schema_name, t.name as table_name, SUM(p.rows) AS SumOfRows
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.partitions p ON p.object_id = t.object_id
WHERE s.name = N'dbo' AND t.name LIKE N'BB%'
GROUP BY s.name, t.name
但rows
列不准确(根据MSDN)。
2)或者,如果我想要准确的数字,那么我会使用COUNT(*)
因此
DECLARE @SqlStatement NVARCHAR(MAX) = N''
SELECT @SqlStatement =
@SqlStatement
+ N' UNION ALL SELECT '
+ '''' + full_name + ''''
+ N' AS full_name, COUNT(*) AS row_count FROM ' + full_name
FROM (
SELECT QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) AS full_name
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
WHERE s.name = N'dbo' AND t.name LIKE N'BB%'
) s
SET @SqlStatement = STUFF(@SqlStatement, 1, 10, N'')
EXEC sp_executesql @SqlStatement