Friday, May 9, 2008

DeFragmenting Heap Tables.


    Ever wanted to know how to deal with fragmentation on tables without any index/primary key, the heap tables. Here is a script that one of my friend forwarded to me when I asked him this question.

    BEGIN TRAN

            ALTER TABLE [dbo].[XYX_HeapTable] ADD [c] VARCHAR(1) NULL
            CREATE  CLUSTERED  INDEX [i] ON [dbo].[XYX_HeapTable] ([c]) WITH  FILLFACTOR = 100
            DROP INDEX [dbo].[XYX_HeapTable].[i]
            ALTER TABLE [dbo].[XYX_HeapTable] DROP COLUMN [c]

    COMMIT TRAN
    Where XYZ_HeapTable is a name of the table which in heap (no primary key nor indexes on it). I wanted to test run this script to see the effectiveness of the above script. So I wrote down the following batch of scripts,

    USE Tempdb

    GO

    CREATE TABLE XYX_HeapTable (
            TrackId INTEGER,
            Fname VARCHAR(200),
            Sname VARCHAR(200)
    )

    SET NOCOUNT ON

    DECLARE @iCount INTEGER
    SET @iCount = 0
    WHILE @iCount < 10000
    BEGIN
            INSERT INTO XYX_HeapTable VALUES (@iCount, '234234234234232432as34234232432dfasdfasdfasdfasdfasdfasdfasdfasdf', 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf')

            SET @iCount = @iCount +1
    END


    DECLARE @ObjectId INTEGER
    SELECT @ObjectId = OBJECT_ID('XYX_HeapTable')

    DBCC SHOWCONTIG (@ObjectId,0) WITH TABLERESULTS, FAST

    GO

    BEGIN TRAN

            ALTER TABLE [dbo].[XYX_HeapTable] ADD [c] VARCHAR(1) NULL
            CREATE  CLUSTERED  INDEX [i] ON [dbo].[XYX_HeapTable] ([c]) WITH  FILLFACTOR = 100
            DROP INDEX [dbo].[XYX_HeapTable].[i]
            ALTER TABLE [dbo].[XYX_HeapTable] DROP COLUMN [c]

    COMMIT TRAN

    GO

    DECLARE @ObjectId INTEGER
    SELECT @ObjectId = OBJECT_ID('XYX_HeapTable')
    DBCC SHOWCONTIG (@ObjectId ,0) WITH TABLERESULTS, FAST

    GO

    DROP TABLE XYX_HeapTable

    Conclusion: I saw good improvement in ScanDensity and ExtentFragmentation after running of the above script, so it works.

No comments:

About Me

By profession I am a Database Administrator (DBA) with total 13 yrs. of experience in the field of Information Technology, out of that 9 yrs as SQL DBA and last 3 years in IBM System i/iSeries and DB2 LUW 9. I have handled Developer, plus production support roles, and I like both the roles. I love and live information technology hence the name "Techonologyyogi" Apart from that I am a small, retail investor, with small investments in India and United States in the form of Equity holdings via common stocks. Don't ask me if I have made money, I have been loosing money in stocks.