Enable row level compression on all tables and indexes

compressionsql-server-2008

One of the (optional) requirements for the Works With SQL Server 2008 test is that row level compression is enabled on all tables and indexes. We have an existing database with a lot of tables and indexes already created. Is there an easy way to enable compression on all these tables and indexes?

Here is the script I ended up making from splattne's recommendation.

select 'ALTER TABLE [' + name + '] REBUILD WITH (DATA_COMPRESSION = ROW);'   
from   sysobjects   where  type = 'U' -- all user tables
UNION
select 'ALTER INDEX [' + k.name + '] ON [' + t.name + '] REBUILD WITH (DATA_COMPRESSION = ROW);'
from   sysobjects k
join sysobjects t on k.parent_obj = t.id
   where  k.type = 'K' -- all keys
    AND t.type = 'U' -- all user tables

Best Answer

I've just used the Works With SQL Server Tool to test after compressing using the a_hardin-splattne script. The test failed because several indexes were not compressed.

The "sysobjects" view includes some but not all of the indexes. We need "sysindexes" instead. Thanks to the anonymous poster at aspfaq.com for this index insight. We also want to ignore user-defined functions.

SELECT 'ALTER TABLE [' + name + '] REBUILD WITH (DATA_COMPRESSION = ROW);' + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10) 
FROM  sysobjects  WHERE type = 'U' -- all user tables
UNION
SELECT  'ALTER INDEX [' + i.name + '] ON [' + OBJECT_NAME(i.id) + '] REBUILD WITH (DATA_COMPRESSION = ROW);' + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10) 
FROM 
    sysindexes i 
    inner join sysobjects o on o.name = OBJECT_NAME(i.id)
WHERE 
    (i.indid BETWEEN 1 AND 254) 
    AND (i.Status & 64)=0 
    AND OBJECTPROPERTY(i.id, 'IsMsShipped') = 0 
    AND NOT o.type in ('TF','FN')