Find out the tables having the largest size in your database using SQL Server 2005

In one of the previous articles, we saw how to Display the size of all tables in Sql Server 2005 .

In this article, we will see how to find out the largest tables in your database and display the results in a sorted order

USE YourDB

DECLARE @TblNames Table
(
COUNTER INT IDENTITY(1,1),
tbl_name nvarchar(100) NULL,
row varchar(10),
reserved varchar(10),
data varchar(10),
index_size varchar(10),
unused varchar(10)
)
DECLARE @ROWCOUNT INT
DECLARE @I INT
DECLARE @str nvarchar(100)
SET @I = 1
INSERT INTO @TblNames(tbl_name) SELECT name FROM sys.Tables
SET @ROWCOUNT = @@ROWCOUNT
WHILE @I <= @ROWCOUNT
BEGIN
SELECT @str = tbl_name FROM @TblNames WHERE COUNTER = @I
INSERT INTO @TblNames EXEC sp_spaceused @str
SET @I = @I +1
END

-- Display results in Sorted order

SELECT tbl_name as TableNm, CAST(REPLACE(data, ' kb', '') as int) as TblSize,
CAST(REPLACE(index_size, ' kb', '') as int) as IdxSize
FROM @tblNames ORDER BY TblSize DESC

5 comments:

  1. I really do appreciate the information. However, I found out that I could delete the "COUNTER" row after it was assigned to the @str variable. This keeps the data from being duplicated when selecting the data afterwards during the order by. Here is the additional in-between the two lines already from your code. Hence, the DELETE row is what you were missing.

    SELECT @str = tbl_name FROM @TblNames WHERE COUNTER = @I

    DELETE FROM @TBLNAMES WHERE COUNTER = @I

    INSERT INTO @TblNames EXEC sp_spaceused @str

    Thought this might help someone, but otherwise your code was awesome! Thanks, ICE

    ReplyDelete
  2. Hi ICE,

    Thanks for your code. I appreciate it.

    ReplyDelete
  3. I modified your script because a lot of my tables live in schemas other than dbo....thanks for the script though worked great.

    Script:
    DECLARE @TblNames Table
    (
    COUNTER INT IDENTITY(1,1),
    tbl_name nvarchar(100) NULL,
    row varchar(10),
    reserved varchar(10),
    data varchar(10),
    index_size varchar(10),
    unused varchar(10)
    )
    DECLARE @ROWCOUNT INT
    DECLARE @I INT
    DECLARE @str nvarchar(100)
    SET @I = 1

    INSERT INTO @TblNames(tbl_name)
    SELECT s.name + '.' + st.name
    FROM sys.Tables st
    join sys.schemas s on st.schema_id = s.schema_id;

    SET @ROWCOUNT = @@ROWCOUNT

    WHILE @I <= @ROWCOUNT
    BEGIN

    SELECT @str = tbl_name
    FROM @TblNames
    WHERE COUNTER = @I;

    INSERT INTO @TblNames EXEC sp_spaceused @str;

    SET @I += 1;

    END

    -- Display results in Sorted order

    SELECT tbl_name as TableNm, CAST(REPLACE(data, ' kb', '') as int) as TblSize,
    CAST(REPLACE(index_size, ' kb', '') as int) as IdxSize
    FROM @tblNames ORDER BY TblSize DESC

    ReplyDelete
  4. I received "Query completed with errors" while running this query. please advise.

    ReplyDelete