0

I want to run a weekly extract from a SQL Server database using SQLCMD under SQL Agent. Because I need to save multiple extracts in the same share, I want to use the current date as part of the extract's file name. When doing this from the command line, I use:

sqlcmd -S POC -i "\\org-data\data\dept\share\registry\SQLCMD\extractdata.sql" -s "|" -W -h-1 -o "\\org-data\data\dept\share\registry\Extracts\extractdata.%date:~-4,4%%date:~-10,2%%date:~-7,2%.txt"

and it works perfectly.

When I place the same statement into a CmdExec under SQL Agent, my date becomes a syntax error -- ("The filename, directory name, or volume label syntax is incorrect")

How do others handle this? Thanks.

2 Answers 2

5

Try using the SQL Server Agent tokens. They are described in MSDN article, "Use Tokens in Job Steps". The DATE token provides the current date in YYYYMMDD format. For your example use:

"...\Extracts\extractdata.$(ESCAPE_DQUOTE(DATE)).txt"
Sign up to request clarification or add additional context in comments.

2 Comments

I wanted to mention that this post was helpful for me today - I needed to make the output file name of a job step have a date stamp and the SQL Server Agent tokens example was a fast solution with zero coding. So, I just put the token in the "Output File Name" box on the advanced tab like this: C:\Users\Public\Documents\Test_$(ESCAPE_DQUOTE(DATE)).txt
This worked well for me. Not sure why this isn't accepted as answer
0

This isn't working for me

echo off
sqlcmd -m 1 -S 10.108.96.210\QA832 -U Exception -P Password1 -i E:\KCM_UAT\Exception.sql -o C:\Test_$(ESCAPE_DQUOTE(DATE)).txt  -W -h-1 -s "    "
set /p delExit=Press the ENTER key to exit...:

The file is written out like this

Test_$(ESCAPE_DQUOTE(DATE)).txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.