INFO: Using Return Codes with xp_cmdshell Stored Procedure (184039)



The information in this article applies to:

  • Microsoft SQL Server 4.2x
  • Microsoft SQL Server 6.0
  • Microsoft SQL Server 6.5
  • Microsoft SQL Server 7.0
  • Microsoft SQL Server 2000 (all editions)

This article was previously published under Q184039

SUMMARY

This article describes the behavior that you will observe when you use return codes with the xp_cmdshell stored procedure on different versions of Microsoft SQL Server.

MORE INFORMATION

The "Microsoft SQL Server Transact-SQL Reference" includes an example of the xp_cmdshell extended stored procedure and how to use return codes from it in a batch to perform conditional execution. It is documented incorrectly, however.

Using the following modified example, you can expect different behavior Based on which version of Microsoft SQL Server you are using.

Example

   DECLARE @result int
   EXEC @result = xp_cmdshell "dir *.exe"
   /* The original result was evaluated against 1 */ 
   IF (@result = 0)
      PRINT 'Success'
   ELSE
      PRINT 'Failure'
				

Behavior in Version 4.21 and 6.0

The return code in xp_cmdshell in versions 4.21 and 6.0 is limited in that it returns a value of either 0 or 1 depending on whether the command was executed successfully. The return code does not provide the actual exit code of the command being called.

Behavior in Version 6.5 and Later

In version 6.5 and later, xp_cmdshell is improved. It returns the actual exit code from the command being executed. This provides a much more useful mechanism in using the return code inside a batch or stored procedure.

Modification Type:MinorLast Reviewed:3/14/2005
Keywords:kbinfo KB184039