Thursday, August 14, 2008

How to run all SQL scripts in a folder

Suppose you have a set of SQL scripts for SQL Server that you want to run regularly. Place them all in a single folder, and then you can run a single command file to execute them all.

Here is an example:

for %z in (c:\Scripts\*.sql) do osql -S computername\instancename -U username -P password -d databasename -n -b -i %z

You can also do the same thing, except connect to the SQL Server using Windows Authentication instead of a SQL Server login using the -E parameter instead of -U and -P:

for %z in (c:\Scripts\*.sql) do osql -S computername\instancename -E -d databasename -n -b -i %z

Those dashed parameters (-S, -U, -P, -E, -d, -n, -b, -i) are for OSQL. Case matters. For example, -d is not the same as -D.

You can see all the possible OSQL parameters by running the command OSQL ?. For quick reference, here's a screenshot of what's returned when you run OSQL ?:


No comments: