Executes a given command string as an operating-system command shell and returns any output as rows of text.
xp_cmdshell command_string [, no_output]
where
Be aware that when you grant execute permission for xp_cmdshell to users, the users will be able to execute any operating-system command at the Windows NT command shell that the account running SQL Server (typically local system) has privilege to execute.
To restrict xp_cmdshell access to users who have administrator permission on the Windows NT-based computer where SQL Server is running, use SQL Setup or SQL Enterprise Manager to set the server options, selecting the "xp_cmdshell - Impersonates Client" option. With this option selected, only users who have connected to SQL Server via a trusted connection and are members of the local Administrators group on that computer are allowed to use xp_cmdshell. The commands run by xp_cmdshell continue to execute in the server's security context.
This example shows the xp_cmdshell extended stored procedure executing a directory command.
EXEC master..xp_cmdshell "dir *.exe"
This example shows the use of xp_cmdshell in a stored procedure. This example notifies users (with net send) that SQL Server is about to be shut down, pauses the server (with net pause), and then shuts the server down (with net stop):
CREATE PROC shutdown10 AS EXEC xp_cmdshell "net send /domain:SQL_USERS 'SQL Server shutting down in 10 minutes. No more connections allowed.'", no_output EXEC xp_cmdshell "net pause sqlserver" WAITFOR DELAY "00:05:00" EXEC xp_cmdshell "net send /domain: SQL_USERS 'SQL Server shutting down in 5 minutes.'", no_output WAITFOR DELAY "00:04:00" EXEC xp_cmdshell "net send /domain:SQL_USERS 'SQL Server shutting down in 1 minute. Log off now.'", no_output WAITFOR DELAY "00:01:00" EXEC xp_cmdshell "net stop sqlserver", no_output
This example uses xp_cmdshell to execute a command string without returning the output to the client.
EXEC xp_cmdshell "copy c:\sqldumps\pubs.dmp \\server2\backups\sqldumps", NO_OUTPUT
In this example, the xp_cmdshell extended stored procedure also suggests return status.
DECLARE @result int EXEC @result = xp_cmdshell "dir *.exe" IF (@result = 1) PRINT "Success" ELSE PRINT "Failure"
Execute permission defaults to the system administrator, who can grant permission to other users.
CREATE PROCEDURE | EXECUTE |
CREATE TRIGGER |