SQL Server – Add Date/Time to output file of BCP / SQLCMD (2)
Last time I posted about How you can add date/time to output file name, in which I used xp_cmdshell to execute the BCP/SQLCMD command using TSQL, which means we need to have xp_cmdshell server feature enabled for that solution work. There is a workaround available to that solution when xp_cmdshell is not enabled.
You can also run BCP/SQLCMD command on command prompt (cmd.exe) and append date/time to output file name. You can use below commands:
SQLCMD command to add date/time to output filename:
SQLCMD -S (local) -E -d SqlAndMe -q "EXEC ExportData" -o MyFile_%date:~6,4%%date:~3,2%%date:~0,2%_%time:~0,2%%time:~3,2%.txt
BCP command to add date/time to output filename:
bcp "EXEC ExportData" queryout MyFile_%date:~6,4%%date:~3,2%%date:~0,2%_%time:~0,2%%time:~3,2%.txt -S (local) -T -d SqlAndMe -c
You can use ECHO command to verify the file name:
How this works:
On command prompt %date% return current date in short format. The ":~6,4" part is like a SUBSTRING function which returns 4 characters starting from position 6, which returns year. Similarly, we are retrieving month, day, hour, minutes using same function and appending all of this together to generate the file name in format "MyFile_YYYYMMDD_HHMM.txt"
Hope This Helps!
This is a personal weblog. The opinions expressed here are my own and not of my employer. For accuracy and official references refer to MSDN, Microsoft TechNet, Books Online. I or my employer do not endorse any of the tools / applications / books / concepts mentioned here on my blog. I have simply documented my personal experiences on this blog.
- Backup & Recovery (11)
- Catalog Views (25)
- Certification (1)
- Common Table Expressions (6)
- Database Mail (1)
- Management Studio (38)
- Management Views and Functions (11)
- Partitioning (3)
- Service Pack Releases (2)
- SQL Agent (7)
- SQL Bugs (2)
- SQL Configuration (30)
- SQLServer (164)
- Uncategorized (1)
- Undocumented Functions (21)
- Working With Data (14)