xp_cmdshell <command>[, no_output] [return_status | no_wait]
<command>
是操作系统命令字符串;最长为 8192 个字节。
no_output
如果指定,则不显示命令的任何输出。
return_status
如果指定,则返回 command 参数中指定的操作系统命令的完成状态。如果不使用此参数,则返回值为 0 表示成功,为 1 则表示失败。
no_wait
如果指定,则 xp_cmdshell 操作会立即将控制权还给调用方,指定的命令会作为后台进程执行。您不会看到输出,返回的结果仅反映作为后台进程启动命令时是成功还是失败,不反映进程本身是成功还是失败。
以静默方式将 C 驱动器上名为 log 的文件复制到 A 驱动器上名为 log.0102 的文件:
xp_cmdshell 'copy C:\log A:\log.0102', no_output
执行操作系统的 ls 命令,并将列表目录内容作为一行数据返回:
xp_cmdshell 'ls'
使用 xp_cmdshell 时,还存在一些其它注意事项:
grant execute on xp_cmdshell to joe
<command> 是用 xp_cmdshell 运行的命令的名称:
exec @ret = xp_cmdshell <command>
如果 xp_cmdshell 执行成功,exec @ret = xp_cmdshell <command> 返回的值为 0。如果 xp_cmdshell 执行失败,exec @ret = xp_cmdshell <command> 返回的值为 1。
<command> 是用 xp_cmdshell 运行的命令的名称:
exec @ret = xp_cmdshell <command>, return_status
exec @ret = xp_cmdshell <command>, return_status 会使 xp_cmdshell 返回该命令的实际退出状态码。如果发生故障导致 XP Server 无法运行该命令,xp_cmdshell 将返回值 1。如果该命令运行成功,xp_cmdshell 将返回值 0。
如果该命令成功,exec @ret = xp_cmdshell <command> 将返回值 0。如果该命令失败,exec @ret = xp_cmdshell <command> 将返回值 1。
> 注意
exec @ret = xp_cmdshell <command> 和 exec @ret = xp_cmdshell <command>, return_status 都是向后兼容的。不使用 return_status 参数的旧存储过程将 exec @ret = xp_cmdshell <command>, return_status 视为 exec @ret = xp_cmdshell <command>。
此外,no_output 参数仍可与 return_status 搭配使用,顺序不限。
create existing table xpoutput
(
cmdstr varchar(255) null
)
external procedure at "THIS...xp_cmdshell"
select cmdstr from xpoutput where cmdstr = "date"
如果不使用 cmdstr,则会看到一条错误消息。