Using LIKE wildcard with % operator in SQL xp_cmdshell

103 Views Asked by At

I am trying to use the % operator in the xp_cmdshell like below.

DECLARE @OutputFilePath nvarchar(max);
SET @OutputFilePath = '\\shared data\Everyone Share\';
DECLARE @ExportSQL nvarchar(max);
SET @ExportSQL = N'
EXEC master.dbo.xp_cmdshell
  ''bcp "SELECT FileID, NAME FROM [Process].[dbo].[Vendor] WHERE FileName LIKE ''%'' + AAMG + ''%''" queryout "' + @OutputFilePath + '\OutputData.csv" -T -c -t -S WIN-db02''
' 

EXEC(@ExportSQL)

But it is throwing me an error saying Incorrect syntax near '%'

If i just remove the LIKE part, the entire code works perfectly fine.

1

There are 1 best solutions below

4
Squirrel On BEST ANSWER

(reproduce here from comments. it is easier to read here)

You need to double up the single quote around the %

SET @ExportSQL = N'
EXEC master.dbo.xp_cmdshell
  ''bcp "SELECT FileID, NAME FROM [Process].[dbo].[Vendor] WHERE FileName LIKE ''''%'''' + AAMG + ''''%''''" queryout "' + @OutputFilePath + '\OutputData.csv" -T -c -t -S WIN-db02''
'

Looks like AAMG is a constant string and not a column name. In this case, change the dynamic query to

LIKE ''''%AAMG%''''"