I recently experienced this issue on during ETL processing.
I could have scripted out all of the index rebuilds for the table and then added to an Execute SQL task within SSIS. However, if any index should be deleted or renamed, then the Execute SQL task would fail, and the ETL would stop. Also, if we added new indexes, they would not get rebuilt until we added the index to the the Execute SQL task.
So I wrote a stored procedure to rebuild all of the indexes on the a table, or, just one index on a table.
I wanted to share that procedure with you, since I think this may be a common scenario.
peace
-- =============================================
-- spwRebuildTableIndexes
--
-- Author: Bob Pearson
-- Create date: 2013-03-14
-- Description: Rebuilds specified index or all indexes on a table
--
-- Updates
-- Date Who What
-- -------- ---- ----------------------------
--
-- =============================================
ALTER PROCEDURE [dbo].[spwRebuildTableIndexes]
@TableName varchar(100),
@IndexName varchar(100) = null
AS
BEGIN
Set NOCOUNT ON;
Declare @SQL varchar(max) = '';
if @IndexName is not null
BEGIN
Select @SQL = 'Alter Index ' + @IndexName + ' on ' + @TableName + ' REBUILD;';
Execute (@SQL);
print @TableName + '.' + @IndexName + ' Rebuilt...'
Return;
END
Declare cur cursor for
Select i.name
from sys.indexes i
inner join
sys.objects o
on i.object_id = o.object_id
where o.name = @TableName and o.type = 'U'
for read only;
Open Cur;
Fetch Next from Cur into @IndexName;
While @@FETCH_STATUS = 0
BEGIN
Select @SQL = 'Alter Index ' + @IndexName + ' on ' + @TableName + ' REBUILD;';
Execute (@SQL);
print @TableName + '.' + @IndexName + ' Rebuilt...'
Fetch Next from Cur into @IndexName;
END
Close Cur;
Deallocate Cur;
END
No comments:
Post a Comment