Tuesday, March 16, 2010

SQL Express Query results to csv with batch file

SQL Express management tool has limited functionality and it lacks the process of scheduling backups or any specific query tasks.

This particular example will execute a query and save it as *.csv file everyday.

//batch file start....


@echo off


set Today=%date:~10,4%%date:~4,2%%date:~7,2%
set Now=%time:~0,2%%time:~3,2%%time:~6,2%



sqlcmd -S localhost -d HistorianDB -E -Q "select recordnumber, name, timestamp, data from TrendLogView" -o "historianBkp-%Today%-%Now%.csv" -s"," -w600


cls
exit


//--end

Save this file with .batch extension and when executed creates a .csv file with datetime stamp. Now to automate this batch file execution you could use the windows scheduled task to do it.