SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE SQDR.REBUILDINDEXES
	@tschema nvarchar(128) ,
	@tname nvarchar(128)
	
AS
BEGIN
	
DECLARE @my_sql2 NVARCHAR(200);
DECLARE @sql nvarchar(500);

 set @sql =  'DECLARE cur_rebuild CURSOR FOR SELECT ''ALTER INDEX '' +  i.name + '' ON '' + s.name + ''.'' + t.name + '' REBUILD '' FROM sys.indexes i 
   JOIN sys.tables t ON i.object_id = t.object_id 
   INNER JOIN sys.schemas s ON t.schema_id = s.schema_id 
   WHERE i.is_disabled = 1 and t.name=''' + N'@tname' + ''' and s.name=''' + N'@tschema' + ''' ORDER BY t.name, i.name;'

EXEC sp_executesql @sql
OPEN cur_rebuild;
FETCH NEXT FROM cur_rebuild INTO @my_sql2;
WHILE @@FETCH_STATUS = 0
   BEGIN
      EXECUTE sp_executesql  @my_sql2;
      FETCH NEXT FROM cur_rebuild INTO @my_sql2;
   END;
CLOSE cur_rebuild;
DEALLOCATE cur_rebuild;

END

