我一直在网上搜索一些内容,看来从XP_CMDSHELL获取结果的唯一方法是将它们存储到临时表中。真的没有更简单的方法吗?

从专家交流:


不,xp_cmdshell不会从exe返回任何信息。并且您必须使用以下内容
语法,如果您不在master数据库中运行它。主..xp_cmdshell。你不得不
向您的用户授予在master数据库中执行此过程的权限。你将不得不
您的exe会自行插入信息,因为它无法将信息返回给
叫它。


和...

虽然@result仅从xp_cmdshell获取返回值,但是您可以捕获结果
通过直接插入到表中来执行命令...像这样:

嗯...

set nocount on
declare  @filepath   varchar(255),
         @cmd        varchar(255),
         @rc         int

select   @filepath = 'c:\temp\'
select   @cmd      = 'dir ' + @filepath + '~*.tmp'

create table #output (output varchar(255) null)
insert #output exec @rc = master..xp_cmdshell @cmd
select * from #output where output is not null
drop table #output

最佳答案

没有简单的方法可以从xp_cmdshell捕获STDOUT / STDERR反馈。至少有一种选择,但不能归类为更简单的选择:
作为命令的一部分,可以将命令的输出重定向到文本文件,然后使用OPENROWSET读取文本文件。

顺便说一句,上面发布的脚本中至少有一个错误。 xp_cmdshell的文档状态为它返回命令输出为nvarchar(255)。
此外,临时表应具有一个标识列,否则结果可能无法以正确的顺序显示:

...
create table #output (id int identity(1,1), output nvarchar(255) null)
insert #output (output) exec @rc = master..xp_cmdshell @cmd
select * from #output where output is not null order by id
drop table #output

关于sql-server - 从XP_CMDSHELL获取结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9501192/

10-11 21:55