Search code examples
for-loopbatch-fileiterationsqlcmd

SQLCMD in a for loop


I have recently discovered that i am not able to fire the following command from a batch file:

for %%G in (%path%) do sqlcmd /S <my-server> /d <my-database> /E /i "%%G" -b

It tells me, that it could not find the command "sqlcmd". However, if I run this command directly in the command prompt (by removing one % of each pair) it works!

Why is that and how can I make it work with my batch file?

Update:

This is the following code I got in my batch file:

@echo off
set mypath=%~dp0
set mypath=%mypath%sql

for %%G in ("%mypath%") do echo %%G & sqlcmd /S sample-server /d sample-database /E /i "%%G" -b

pause

Solution

  • Here's your problem:

    set path=%~dp0
    set path="%path%sql\"
    

    PATH is the sequence of directories Windows uses to search for executables, so when you change it, sqlcmd can no longer be found.

    Simply use another variable name. Mypath seems good...