batch file

Run SQL scripts from a folder using sqlcmd

This is a very short post about a very useful tip. I came across here on   stackoverflow and it certainly deserves a post. Many thanks to the answerer and I think this is his blog. I already follow it and would highly encourage you if you are interested in SQL Server.

Very often I need to execute all the SQL scripts from a folder. There are tools out there to do this but I wanted something very simple, like a batch command. So let’s say you want to execute all the SQL scripts from folder ‘D:\Scripts’  on server ‘localhost’ and on database ‘playbox’. Here are the steps

1. Open command prompt.

2. Navigate to the scripts folder.

3. Type the following command.

for %f in (*.sql) do sqlcmd /S localhost /d playbox /E /i "%f"

What this will do is iterate through all the .sql files in the folder and execute each one using sqlcmd. /S, /d, /E  are sqlcmd parameters. The beauty of this solution is you don’t have to install anything. Wrap a few of these statements in a batch file and you can execute statements from different folders in one go. Neat!!!