SQL Server 2008 R2 - sqlcmd bat file to run a batch of sql queries in folder but they are not running in order of file name

人盡茶涼 提交于 2021-01-27 20:16:32

问题


I have a bunch of written sql scripts that I have written and I was looking to run as a batch in order in a folder. After reading up I've resorted to creating a bat file which includes using the sqlcmd. For this particular set of scripts, when i run the bat it doesn't seem to run in order. I have no idea what is going on as I've tried renaming the sql scripts numerically with a prefix number in the beginning, tried using letters, and even renaming the whole script to just a number/letter using windows explorer.

The process might look something like this A.sql - B.sql - C.sql - D.sql - F.sql - G.sql - E.sql

Any ideas as to what I am missing or how i am renaming these files incorrectly? Thanks

what I have in my bat file

for %%G in (*.sql) do sqlcmd /S W-VAN-A124178\HAZUSPLUSSRVR /d 
BC_Exposure_2016 -E -i"%%G"
pause

回答1:


You could parse the output of the dir command which you can modify so that the files appear in alphabetical order. For that you could use dir /A-D /B /ON:
/A-D excludes directories
/B excludes a lot of messy additional information that is annoying to work around while parsing
/ON orders by name

So to modify your code:

for /f %%G in ('dir /A-D /B /ON') do (
  sqlcmd /S W-VAN-A124178\HAZUSPLUSSRVR /d BC_Exposure_2016 -E -i"%%G"
)
pause

should work. I put parenthesis around the loop. For once because I am used to it and because the code was split into two lines else.



来源:https://stackoverflow.com/questions/46292805/sql-server-2008-r2-sqlcmd-bat-file-to-run-a-batch-of-sql-queries-in-folder-but

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!