我正在寻找一个SQL脚本,可用于确定是否有任何数据(即行计数)在给定数据库的任何表。
这样做的目的是在存在任何行(在任何数据库中)的情况下重新具体化数据库。
这里所说的数据库是Microsoft SQL SERVER。
谁能建议一个示例脚本?
我正在寻找一个SQL脚本,可用于确定是否有任何数据(即行计数)在给定数据库的任何表。
这样做的目的是在存在任何行(在任何数据库中)的情况下重新具体化数据库。
这里所说的数据库是Microsoft SQL SERVER。
谁能建议一个示例脚本?
当前回答
在Azure上工作,不需要存储过程。
SELECT t.name AS table_name
,s.row_count AS row_count
FROM sys.tables t
JOIN sys.dm_db_partition_stats s
ON t.OBJECT_ID = s.OBJECT_ID
AND t.type_desc = 'USER_TABLE'
AND t.name NOT LIKE '%dss%' --Exclude tables created by SQL Data Sync for Azure.
AND s.index_id IN (0, 1)
ORDER BY table_name;
信贷。
其他回答
在Azure上工作,不需要存储过程。
SELECT t.name AS table_name
,s.row_count AS row_count
FROM sys.tables t
JOIN sys.dm_db_partition_stats s
ON t.OBJECT_ID = s.OBJECT_ID
AND t.type_desc = 'USER_TABLE'
AND t.name NOT LIKE '%dss%' --Exclude tables created by SQL Data Sync for Azure.
AND s.index_id IN (0, 1)
ORDER BY table_name;
信贷。
这是我最喜欢的SQL 2008解决方案,它将结果放入一个“TEST”临时表,我可以使用它来排序并获得我需要的结果:
SET NOCOUNT ON
DBCC UPDATEUSAGE(0)
DROP TABLE #t;
CREATE TABLE #t
(
[name] NVARCHAR(128),
[rows] CHAR(11),
reserved VARCHAR(18),
data VARCHAR(18),
index_size VARCHAR(18),
unused VARCHAR(18)
) ;
INSERT #t EXEC sp_msForEachTable 'EXEC sp_spaceused ''?'''
SELECT * INTO TEST FROM #t;
DROP TABLE #t;
SELECT name, [rows], reserved, data, index_size, unused FROM TEST \
WHERE ([rows] > 0) AND (name LIKE 'XXX%')
SELECT
sc.name +'.'+ ta.name TableName, SUM(pa.rows) RowCnt
FROM
sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
SELECT
SUM(sdmvPTNS.row_count) AS [DBRows]
FROM
sys.objects AS sOBJ
INNER JOIN sys.dm_db_partition_stats AS sdmvPTNS
ON sOBJ.object_id = sdmvPTNS.object_id
WHERE
sOBJ.type = 'U'
AND sOBJ.is_ms_shipped = 0
AND sdmvPTNS.index_id < 2
GO
从information_schema中选择所有行。表视图,并为从该视图返回的每个条目发出count(*)语句。
declare c_tables cursor fast_forward for
select table_name from information_schema.tables
open c_tables
declare @tablename varchar(255)
declare @stmt nvarchar(2000)
declare @rowcount int
fetch next from c_tables into @tablename
while @@fetch_status = 0
begin
select @stmt = 'select @rowcount = count(*) from ' + @tablename
exec sp_executesql @stmt, N'@rowcount int output', @rowcount=@rowcount OUTPUT
print N'table: ' + @tablename + ' has ' + convert(nvarchar(1000),@rowcount) + ' rows'
fetch next from c_tables into @tablename
end
close c_tables
deallocate c_tables