martes, 5 de agosto de 2014

Otra forma de ejecución controlada de sentencias sql / Another form of controlled execution of sql statements

/*
       Otra forma de ejecucion controlada de sentencias sql
       Another form of controlled execution of sql statements

       Cuando debemos ejecutar gran cantidad de sentencias sql desatendido y debemos recolectar los errores
       When we run unattended lot of sql statements and we collect errors
*/


set NOCOUNT on

DECLARE @SQLCommand  VARCHAR  (2000)
DECLARE @NSQLCommand NVARCHAR (2000)
DECLARE @SQLERROR    INT

declare @TableSQL table (Orden INT IDENTITY , SQL varchar (4000) )
declare @TableSQLErr table ( ErrorNumber int,  ErrorDesc varchar (4000), SQL varchar (4000) )


/*
       En esta seccion insertaremos en la variable tabla @TableSQL todos los scripts que debemos ejecutar,
       aqui un ejemplo de reindexado de tablas

       In this section we will insert into @ table Variable TableSQL all scripts that we run,
       here an example of re-indexing of tables
*/
insert into @TableSQL select 'ALTER INDEX ALL ON ' + name + ' REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = ON);' from sys.objects where type = 'U'

/********************Se ejecutan todas las sentencias generadas previamente*******************/
DECLARE FKPK_cursor CURSOR FOR
       select SQL from @TableSQL order by orden
  OPEN FKPK_cursor;

 FETCH NEXT FROM FKPK_cursor
   INTO @SQLCommand

  WHILE @@FETCH_STATUS = 0

  BEGIN
       BEGIN TRY
             Set @NSQLCommand = Convert(nvarchar(2000), @SQLCommand)
        --print @NSQLCommand
        EXEC sp_executesql @statement = @NSQLCommand
       END TRY
       BEGIN CATCH
             set @SQLERROR = @@error
             Insert into @TableSQLErr values (@SQLERROR, ERROR_MESSAGE(), @SQLCommand)
       END CATCH;
    FETCH NEXT FROM FKPK_cursor
      INTO @SQLCommand
  END

CLOSE FKPK_cursor;
DEALLOCATE FKPK_cursor;
/*********************************************************************************/

set NOCOUNT OFF

/*
       Resultado: Todas las operaciones ejecutadas
       Result: All transactions executed
 */
Select * from @TableSQL order by orden

/*
       Resultado: Todos errores ocurridos
       Result: All errors
*/

Select * from @TableSQLErr