Processing output from xp cmdshell in SQL Server

From The CA Plex Wiki

Jump to: navigation, search
   CREATE  PROCEDURE dbo.fx_dr_ActiveOrderBackup AS
   BEGIN
       --Create a temporary table to hold the output of the BAT file
       CREATE TABLE #Output (cmdOutput VARCHAR(1024))
       --Execute the BAT file and insert the console output into the temporary table
       INSERT #Output EXEC master..xp_cmdshell 'c:\RodeoFileBackup\Cmd\RodeoBackup.bat'
       
       DECLARE @Count Numeric(9,0)
       SELECT
               @Count = Count(*)
       FROM
               #Output
       WHERE
               cmdOutput <> 'NULL' AND (
               cmdOutput LIKE '%error%' OR
               cmdOutput LIKE '%fail%' OR
               cmdOutput LIKE '%cannot%' OR
               cmdOutput LIKE '%denied%' OR
               cmdOutput LIKE '%invalid%' OR
               cmdOutput LIKE '%refused%'
               )
       EXEC fx_ClearWarningByReference 'FXBACK'
       IF @Count > 0 
       BEGIN
               --Errors occurred - write to Activity log
               EXEC fx_CreateCriticalWarningLog 'B', 0, 'BACKUP: Order export and/or FTP transfer failed', 'FXBACK'
               
               DECLARE Output_cursor CURSOR FOR
               SELECT
                       cmdOutput
               FROM
                       #Output
               WHERE
                       cmdOutput <> 'NULL'
       
               OPEN Output_cursor
               DECLARE @CmdOutput VARCHAR(1024)
               FETCH NEXT FROM Output_cursor INTO @CmdOutput
       
               WHILE @@FETCH_STATUS = 0
               BEGIN
                       EXEC dbo.fx_CreateActivityLog @CmdOutput, 'FXBACK'
                       FETCH NEXT FROM Output_cursor INTO @CmdOutput
               END
               
               CLOSE Output_cursor
               DEALLOCATE Output_cursor
               RAISERROR (50001,18,1)
       
               END
       END
       GO
Personal tools