Search code examples
sqlbatch-filesqlcmd

How to sort the input of a batch file


I'm using the following script to execute a bunch .sql statements.

@echo off
ECHO %USERNAME% started the batch process at %TIME%  >output.txt

for %%s in (*.sql)  do (
sqlcmd.exe  -S.\ -E -i "%%s" >>output.txt
    )
pause

However, I want to make sure the files are sorted (name) because I don't think I can guarantee that the list is in order.


Solution

  • No need to worry, FOR sorts (process) the files by name, but if you want another way you can sort the output file too:

    @echo off
    ECHO %USERNAME% started the batch process at %TIME%  >output.txt
    
    FOR %%s in ("*.sql")  do (sqlcmd.exe -S.\ -E -i "%%s" >> "%TEMP%\output.txt")
    
    TYPE "%TEMP%\output.txt" | SORT > ".\Final_Output.txt"
    
    Pause&Exit