• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4058
  • Last Modified:

xp_cmdshell with variable

this is my script:

BEGIN
DECLARE @ret int
DECLARE @instr sysname
SET @instr='dir'
EXEC @ret = xp_cmdshell @instr
UPDATE dirresults SET result=@ret WHERE id=20
END


the problem is, result always stays empty (even if i change my instruction to something that doesn't exist)

my questions:
a)how can I get the result (0 or 1)?
b) how can I get the result of the dir command (e.g. the directory listing)?
0
grotesmurf2
Asked:
grotesmurf2
3 Solutions
 
ShogunWadeCommented:
? why have you declared your parameter as a sysname as opposed to varchar ?
0
 
Dishan FernandoSoftware Engineer / DBACommented:
CREATE Procedure SampleSP
      /* Param List */
AS
      DECLARE @ERROR int      -- For Hold Error Number
      DECLARE @CMD      varchar(1000)      -- Dts Run Command
BEGIN
      -- Set as No Error
      SET @ERROR = 0
      SET @CMD = 'dir'      
      EXECUTE @ERROR = master..xp_cmdshell @CMD
      -- + Error Checking
      SELECT @ERROR = COALESCE( NULLIF ( @ERROR, 0 ), @@ERROR )
      IF @ERROR <> 0 BEGIN ROLLBACK TRANSACTION RETURN @ERROR END
END
      RETURN @ERROR
GO

this will return 0
0
 
Scott PletcherSenior DBACommented:
*) Make sure you have authority to run xp_cmdshell.  Unless you are on 95/98, you must be sysadmin or have explicit authority to run xp_cmdshell.

*) I seem to be able to get a rc of 0 or 1 from dir without a problem.  Not sure what is going on there, unless it's an authority issue.
*) You can capture the output into a temp table, for example:

CREATE TABLE #dir (dirLine NVARCHAR(255))
INSERT INTO #dir
EXEC @ret = master..xp_cmdshell 'dir' --, NO_OUTPUT
SELECT * FROM #dir
0
 
LowfatspreadCommented:
the output of xp_cmdshell is nvarchar(255)
the return code will be either 0 success or 1 failure (unless win98 when you just get 0)
you don't get the errorlevel directly from the command...


try
  create table #t (tid integer identity(1,1) , cmddata nvarchar(255))
  Insert into #t (cmddata)
    exec  Master..xp_cmdshell @cmd

 select * from #t
0
 
coolmintsCommented:
thank you all...

it must be an authority issue I guess. strange I don't get 0 or 1 as output, but just an empty string... sigh...
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now