參考源:http://sqlforums.windowsitpro.com/web/forum/messageview.aspx?catid=74&threadid=47900&enterthread=y
在使用資料庫的時候,我們有時需要知道資料庫佔用磁碟空間的情況,以前資料庫中每個表的磁碟空間使用方式,下面是擷取這些資訊的方法:
1 資料庫的磁碟空間使用資訊sp_spaceused
2 表的磁碟空間使用資訊sp_spaceused '表的名稱'
3 擷取資料庫所有表的磁碟空間使用資訊CREATE PROC spaceused_simulator
@database_name varchar(128)
AS
DECLARE @cmd varchar(1000),
@bytes int
SET NOCOUNT ON
SELECT @bytes = [low]/1024 FROM master..spt_values
WHERE number = 1
AND type = 'E'
CREATE TABLE #tmp_spaceused (
id int NULL,
tablename varchar(128) NULL,
rows int NULL,
reserved int NULL,
data int NULL,
index_size int NULL,
unused int NULL)
SET @cmd =
'INSERT INTO #tmp_spaceused (id, tablename)
SELECT id, name FROM ' + @database_name + '..sysobjects
WHERE xtype = ''U''
AND name <> ''dtproperties'''
EXEC (@cmd)
SET @cmd =
'UPDATE #tmp_spaceused
SET rows = A.rows
FROM ' + @database_name + '..sysindexes A
WHERE #tmp_spaceused.id = A.id
AND A.indid IN (0, 1)'
EXEC (@cmd)
SET @cmd =
'UPDATE #tmp_spaceused
SET reserved = A.SumReserved
FROM (SELECT id, SUM(reserved) AS SumReserved
FROM ' + @database_name + '..sysindexes
WHERE indid IN (0, 1, 255)
GROUP BY id) AS A
JOIN #tmp_spaceused ON A.id = #tmp_spaceused.id'
EXEC (@cmd)
SET @cmd =
'UPDATE #tmp_spaceused
SET data = C.data
FROM (SELECT A.id, A.SumDpages + ISNULL(B.SumUsed, 0) AS data
FROM (SELECT id, SUM(dpages) AS SumDpages
FROM ' + @database_name + '..sysindexes
WHERE indid IN (0, 1)
GROUP BY id) AS A
LEFT JOIN
(SELECT id, ISNULL(SUM(used), 0) AS SumUsed
FROM ' + @database_name + '..sysindexes
WHERE indid = 255
GROUP BY id) AS B
ON A.id = B.id) AS C
JOIN #tmp_spaceused ON C.id = #tmp_spaceused.id'
EXEC (@cmd)
SET @cmd =
'UPDATE #tmp_spaceused
SET index_size = A.SumUsed - #tmp_spaceused.data
FROM (SELECT id, SUM(used) AS SumUsed
FROM ' + @database_name + '..sysindexes
WHERE indid IN (0, 1, 255)
GROUP BY id) AS A
JOIN #tmp_spaceused ON A.id = #tmp_spaceused.id'
EXEC (@cmd)
SET @cmd =
'UPDATE #tmp_spaceused
SET unused = #tmp_spaceused.reserved - A.SumUsed
FROM (SELECT id, SUM(used) AS SumUsed
FROM ' + @database_name + '..sysindexes
WHERE indid IN (0, 1, 255)
GROUP BY id) AS A
JOIN #tmp_spaceused ON A.id = #tmp_spaceused.id'
EXEC (@cmd)
UPDATE #tmp_spaceused
SET
reserved = reserved * @bytes,
data = data * @bytes,
index_size = index_size * @bytes,
unused = unused * @bytes
SELECT * FROM #tmp_spaceused ORDER BY tablename
GO