一直使用以下的SQL
SET NOCOUNT ON
-- Table row counts and sizes.
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 ''?'''
-- Order by size (need to remove the KB sign).
SELECT *
FROM #t ORDER by cast(SUBSTRING(reserved, 1, LEN(reserved)-2) as Int) desc
DROP TABLE #t
但是今天碰到table名中含有schemas,就看上去怪怪的,
只好改用下面的SQL,还来不及检查发生了什么事,只好头痛医头脚痛医脚
declare @RowCount int, @tablename varchar(100)
declare @Tables table (
PK int IDENTITY(1,1),
tablename varchar(100),
processed bit
)
INSERT into @Tables (tablename)
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']' AS TableName
FROM sys.tables order by TABLENAME asc
declare @Space table (
[id] [int] IDENTITY(1,1) NOT NULL,
name varchar(100), rows nvarchar(100), reserved varchar(100), data char(100), index_size varchar(100), unused varchar(100)
)
select top 1 @tablename = tablename from @Tables where processed is null
SET @RowCount = 1
WHILE (@RowCount <> 0)
BEGIN
print @tablename
insert into @Space exec sp_spaceused @tablename
update @Space set name = @tablename where id = (select top 1 MAX(id) as no from @Space)
update @Tables set processed = 1 where tablename = @tablename
select top 1 @tablename = tablename from @Tables where processed is null
SET @RowCount = @@RowCount
END
update @Space set data = replace(data, 'KB', '')
update @Space set data = cast(data as decimal(10,0)) / 1000
update @Space set data = cast(data as decimal(10,2))
update @Space set reserved = replace(reserved, 'KB', '')
update @Space set reserved = cast(reserved as decimal(10,0)) / 1000
update @Space set reserved = cast(reserved as decimal(10,2))
select name as Tablename, rows, replace(data,' ','') + 'MB' as used, replace(reserved,' ','') + 'MB' as [Reserved] ,index_size,unused from @Space order by convert(decimal(10,2),data) desc