FROM sysobjects
WHERE name = 'sp_spaceused2'
AND TYPE = 'P')
DROP PROCEDURE sp_spaceused2
GO
CREATE PROCEDURE Sp_spaceused2 (@type VARCHAR(2) = 'U',-- The objects type we want size on.
@updateusage VARCHAR(5) = false -- Param. for specifying that
-- usage info. should be updated.
)
AS
CREATE TABLE #spt_space
(
id INT NOT NULL PRIMARY KEY,
name SYSNAME,
ROWS INT NULL,
reserved DEC(15) NULL,
data DEC(15) NULL,
indexp DEC(15) NULL,
unused DEC(15) NULL
)
-- Check the object type.
IF @type NOT IN ( 'U', 'S' ) -- no physical data storage.
BEGIN
RAISERROR(55000,
-1,
-1,
@type)
RETURN ( 1 )
END
-- Check to see if user wants usages updated.
IF @updateusage IS NOT NULL
BEGIN
SELECT @updateusage = Lower(@updateusage)
IF @updateusage NOT IN ( 'true', 'false' )
BEGIN
RAISERROR(15143,
-1,
-1,
@updateusage)
RETURN( 1 )
END
END
IF @updateusage = 'true'
BEGIN
DBCC updateusage(0) WITH no_infomsgs
PRINT ' '
END
SET nocount ON
--id, name, rows
INSERT INTO #spt_space
(id,
name,
ROWS,
data)
SELECT i.id,
o.name,
i.ROWS,
0
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.indid < 2
AND o.TYPE = @type
--reserved
UPDATE #spt_space
SET reserved = r.reserved
FROM (SELECT o.id,
SUM(i.reserved) AS reserved
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.indid IN ( 0, 1, 255 )
AND o.TYPE = @type
GROUP BY o.id) r
WHERE #spt_space.id = r.id
--data
UPDATE #spt_space
SET data = data + r.pages
FROM (SELECT o.id,
Isnull(SUM(i.dpages), 0) AS pages
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.indid < 2
AND o.TYPE = @type
GROUP BY o.id) r
WHERE #spt_space.id = r.id
UPDATE #spt_space
SET data = data + r.used
FROM (SELECT o.id,
Isnull(SUM(used), 0) AS used
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.indid = 255
AND o.TYPE = @type
GROUP BY o.id) r
WHERE #spt_space.id = r.id
--index page
UPDATE #spt_space
SET indexp = r.used - data
FROM (SELECT o.id,
SUM(CONVERT(DEC(15), used)) AS used
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.indid IN ( 0, 1, 255 )
AND o.TYPE = @type
GROUP BY o.id) r
WHERE #spt_space.id = r.id
--unused page
UPDATE #spt_space
SET unused = reserved - r.used
FROM (SELECT o.id,
SUM(CONVERT(DEC(15), used)) AS used
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.indid IN ( 0, 1, 255 )
AND o.TYPE = @type
GROUP BY o.id) r
WHERE #spt_space.id = r.id
--output
SELECT #spt_space.name,
ROWS = CONVERT(CHAR(11), ROWS),
reserved = Ltrim(Str(reserved * d.low / 1024., 15, 0) + ' ' + 'KB'),
data = Ltrim(Str(data * d.low / 1024., 15, 0) + ' ' + 'KB'),
index_size = Ltrim(Str(indexp * d.low / 1024., 15, 0) + ' ' + 'KB'),
unused = Ltrim(Str(unused * d.low / 1024., 15, 0) + ' ' + 'KB')
FROM #spt_space,
MASTER.dbo.spt_values d
WHERE d.NUMBER = 1
AND d.TYPE = 'E'
RETURN 0
GO
-- 'sp_spaceused2'