Thursday, July 25, 2013

Reclaiming unused space from a table

--create a test table

CREATE TABLE dbo.Test
        (
         col1 INT
        ,col2 VARCHAR(50)
        ,col3 VARCHAR(MAX)
        ) ;

--create some test data

DECLARE @cnt INT ;
SET @cnt = 0 ;
WHILE 1 = 1
        BEGIN
                SELECT
                        @cnt = @cnt + 1 ;
                INSERT
                        dbo.Test ( col1,col2,col3 )
                VALUES  (
                         @cnt
                        ,'test row # ' + CAST(@cnt AS VARCHAR(100))
                        ,REPLICATE('A',@cnt)
                        ) ;
                IF @cnt = 1000
                        BREAK ;
        END
--check the size of the table

SELECT
        alloc_unit_type_desc
       ,page_count
       ,avg_page_space_used_in_percent
       ,record_count
FROM
        sys.dm_db_index_physical_stats(
             DB_ID()
            ,OBJECT_ID(N'dbo.Test')
            ,NULL
            ,NULL,'Detailed') ;
 --drop the last column and run check the size of the table (Above Query)

ALTER TABLE dbo.Test DROP COLUMN col3 ;

--We get the same results - 221 data pages, storing 3000 rows, each 89% full - even after dropping the column that consumed the most space.

--reclaim the space from the table run check the size of the table (Above Query)
-- This time we will reclaim space

DBCC CLEANTABLE('TestingPerformance', 'dbo.Test') ;

No comments: