Filename from SQL 2005 Query

5 pts.
Tags:
Batch files
SQL 2005
SQL Query
SQL Server
SQL Server 2005
I have a batch file that runs a SQL query command overnight once a week and outputs the results of that query to a file as a .csv file. The query produces, amongst other things, a week ending date. Is it possible to to name the output file with result of the week ending column in the query. All rows will have the same week ending date in the column. The output file would be something like "NPQ_Asst_2010-11-12.csv"

Software/Hardware used:
SQL 2005

Answer Wiki

Thanks. We'll let you know when a new response is added.

Are you using sqlcmd to execute the query ?

Assuming so, here’s a way to do it ( though I’m sure there must be a cleaner way to do it):

<pre>sqlcmd -U username -P password -S SERVER\INSTANCE -Q “SELECT TOP(1) week_ending_date FROM your_table” -o <b>date.txt</b> -h -1
set /p <b>var</b>= < <b>date.txt</b>
set <b>file</b>=NPQ_Asst_<b>%var%</b>.csv
sqlcmd -U username -P password -S SERVER\INSTANCE -Q “YOUR SQL QUERY” -o <b>file</b></pre>

In summary, it executes a query to read the ending date and puts the result into a temp file, whose contents are then assigned to a variable, which is used to construct the file name.

Hope this helps.

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following