dpalma dpalma - 10 months ago 52
SQL Question

Using for loop bat file windows for multiple command calls

I want to export all data from sql server table to a csv, I know I can get the desired result by:

sqlcmd -S . -d database -E -s, -W -Q "SELECT * FROM TABLENAME" > file.csv

I have many tables, so I want to create a .bat file that do the work for me, I have this:

set "list = A B C D"

for %%x in (%list%) do (
sqlcmd -S . -d database -E -s, -W -Q "SELECT * FROM %%x" > %%x.csv


But I am getting errors I don't know (I am not an expert in bat files). Why this does not work? How can I do what I want?


Spacing is important when using set (unless you're doing math with the /A switch). As written, the variable you're setting isn't %list%. It's %list %. Change your set command as follows:

set "list=A B C D"