sql-serverxp-cmdshell

SQL Server xp_cmdshell query: add variables to command


I have the query working correctly, but I want to be able to add a date value variable within the command.

Here is what I have so far:

DECLARE @varDate DATE

SET @varDate = CAST(DATEADD(day, -1, GETDATE()) AS DATE)

EXEC master..xp_cmdshell 'SQLCMD -E -S "EMERALDSERVER\LASERFICHERIO" -s"," -W -Q "SET NOCOUNT ON EXEC PullSageData.[dbo].[Report_Daily_Superintendent_Jobs]" | findstr /V /C:"-" /B > C:\Laserfiche\import\Reports\Reports_"+@varDate+".csv'

Where the @varDate is located should just replace with yesterdays date.

Example file name:

Reports_2018_10_31.csv

instead it outputs the filename:

Reports+@varDate+.csv

My guess is that entering a variable within single quotes isn't applied with double quotes and + like I have been seeing in so many examples.


Solution

  • You must create a new variable that contains everything and execute from it Example:

    declare @varDate date
    SET @varDate=CAST(DATEADD(day,-1,GETDATE()) as date)
    declare @Script varchar (max) = 'SQLCMD -E -S "EMERALDSERVER\LASERFICHERIO" -s"," -W -Q "SET NOCOUNT ON EXEC PullSageData.[dbo].[Report_Daily_Superintendent_Jobs]" | findstr /V /C:"-" /B > C:\Laserfiche\import\Reports\Reports_varDate.csv'
    declare @cmd varchar(max)= replace(@Script,'@varDate',@varDate)
    EXEC master..xp_cmdshell @cmd