I have been searching the web some and it seems like the only way to get the results from XP_CMDSHELL is to store them into a temp table. Is there really no easier way?
From Experts Exchange:
No, xp_cmdshell will not return any information from the exe. and you have to use the following syntax if you are not in the master database to run it. master..xp_cmdshell. You will have to give your user permission to execute this procedure in the master database. You will have to have your exe insert the information its self because it can not return information to the process that called it.
And...
While @result only gets the return value from xp_cmdshell, you may be able to capture the results of the command by inserting directly into a table... something like this:
ymmv...
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
By default, only sysadmin logins can enable and invoke xp_cmdshell, but a sysadmin login can grant permission to enable and invoke xp_cmdshell to one or a set of non-sysadmin logins.
Here's the actual deprecation warning from Microsoft: This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new development work, and modify applications that currently use this feature as soon as possible.
To determine if xp_cmdshell is enabled, execute the following commands: EXEC SP_CONFIGURE 'show advanced option', '1'; RECONFIGURE WITH OVERRIDE; EXEC SP_CONFIGURE 'xp_cmdshell';
The xp_cmdshell is a very powerful extended procedure used to run the command line (cmd). This is very useful to run tasks in the operative system like copying files, create folders, share folders, etc. using T-SQL.
There is no easier way to capture STDOUT/STDERR feedback from xp_cmdshell
; there is at least one alternative but it couldn't be classed as easier:
It would be possible to redirect the output of the command to a text file as part of the command, then read the text file using OPENROWSET
.
BTW there is at least one error in the script posted above. The docs for xp_cmdshell
state that it returns command output as nvarchar(255).
Also, the temp table ought to have an identity column, otherwise the results may not be displayed in the correct order:
...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With