Tuesday, August 20, 2013

SQL Server Table Space Used

I recently found a bit of SQL that I haven't run across in a while and thought I would share. From time to time I need to know the space used by large tables. In tables that require millions of records, it can be useful. Below is the SQL script that I use to get the space used by each table and the total number of rows in the database.

DECLARE @t TABLE
(
    [name] NVARCHAR(128),
    [rows] int,
    reserved VARCHAR(18),
    data VARCHAR(18),
    index_size VARCHAR(18),
    unused VARCHAR(18)
)

INSERT @t EXEC sp_msForEachTable 'EXEC sp_spaceused ''?'''

SELECT *
FROM   @t

-- # of rows.
SELECT SUM([rows]) AS [rows]
FROM   @t

No comments: