Ahmed Ahmed - 7 months ago 22
SQL Question

Using xp_cmpshell with variable in SQL Server

I want to use

xp_cmdshell
to ping servers. I created a procedure but I have a little problem, I need to select the server IP from table that is already created.

I created a cursor to get the server IP from the table but I don't know how to use the
@ip varchar
variable with ping command.

This syntax didn't work:

execute xp_cmdshell 'ping @ip'

Answer

You cannot reference parameters directly within xp_cmdshell, so you have to concatenate the value when creating the command. I recommend reading: https://msdn.microsoft.com/en-us/library/ms175046.aspx

In your example, you would do something like:

DECLARE @cmd nvarchar(4000);
SET @cmd = 'ping ' + @ip;
EXEC xp_cmdshell @cmd; 
Comments