More....Google....Search

Thursday, December 25, 2008

Move indexes to Other Filegroup in SQL server 2005.

I have seen many peoples having trouble with moving indexes to different file group.There is no such available feature to move all non-clustered indexes to other file gruop for better performance and handel disk threshold.

You can have this procedure executed on production to move indexes to another filegroup.

ALTER PROC uspMoveTableToFileGroup
@TblName VARCHAR(200),
@tblFileGroupName VARCHAR(200),
@indFileGroupName VARCHAR(200) AS

SET NOCOUNT ON
create table #indx (index_name VARCHAR(200), index_description VARCHAR(200), index_keys VARCHAR(200))

INSERT #indx (index_name , index_description , index_keys) EXEC sp_helpindex @TblName


--SELECT 'SELECT ' + '''' + 'Table :' + @TblName + ''''
--SELECT 'SELECT ' + '''' + 'Start Time : ' + '''' + ' + CONVERT(char(25), GETDATE(), 121)' +
-- CHAR(13) + ' GO '
--SELECT 'DECLARE @StartDt DATETIME'
--SELECT 'SET @StartDt = GETDATE()'

SELECT 'CREATE ' +
CASE WHEN CHARINDEX('UNIQUE', index_description, 0) > 0 THEN 'UNIQUE ' ELSE '' END +
CASE WHEN SUBSTRING(index_description,1,3) = 'non' THEN 'NONCLUSTERED ' ELSE 'CLUSTERED ' END +
' INDEX ' +
index_name + CHAR(13) + ' ON ' + 'dbo.[' + @TblName + ']' +
'(' + replace(index_keys, '(-)', ' DESC') + ')' + ' WITH DROP_EXISTING ON '
+ '[' + CASE WHEN SUBSTRING(index_description,1,3) = 'non' THEN @indFileGroupName ELSE @tblFileGroupName END + ']'
FROM #indx


--SELECT 'SELECT ' + '''' + @TblName + ', ' + '''' + ' + CONVERT(char(25), @StartDt, 121)' + '+' +
-- '''' + ', ' + '''' +
-- ' + CONVERT(char(25), GETDATE(), 121) ' + '+' + '''' + ', ' + '''' + '+' +
-- ' CAST(DATEDIFF(ss, @StartDt, GETDATE()) AS VARCHAR(20))' + CHAR(13) + ' GO '

/*
select 'exec uspMoveTableToFileGroup ' +
'''' + name + '''' + ', ' +
'''' + 'Primary' + '''' + ', ' +
'''' + 'INDEX_FG' + ''''
from sysobjects
where xtype = 'U'
*/


Thanks
Ajay
Sr. SQL DBA

No comments: