137

I have a number of .sql files which I have to run in order to apply changes made by other developers on an SQL Server 2005 database. The files are named according to the following pattern:

0001 - abc.sql
0002 - abcef.sql
0003 - abc.sql
...

Is there a way to run all of them in one go?

K.A.D.
  • 3,648
  • 3
  • 34
  • 35

14 Answers14

170

Create a .BAT file with the following command:

for %%G in (*.sql) do sqlcmd /S servername /d databaseName -E -i"%%G"
pause

If you need to provide username and passsword

for %%G in (*.sql) do sqlcmd /S servername /d databaseName -U username -P 
password -i"%%G"

Note that the "-E" is not needed when user/password is provided

Place this .BAT file in the directory from which you want the .SQL files to be executed, double click the .BAT file and you are done!

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Vijeth
  • 1,716
  • 1
  • 11
  • 2
  • 2
    when i executed the batch file some authentication problem occurs saying "Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.". Is there a way to provide username and password too like as server name and database? – Sanjay Maharjan Aug 04 '15 at 04:17
  • 12
    @SanjayMaharjan use -U for user and -P for password, like: `for %%G in (*.sql) do sqlcmd /S servername /d databaseName -U username -P "password" -i"%%G"` – Rickedb Dec 12 '16 at 21:25
  • 1
    how can i put the output to separate files using -o ? whenever i use like -o temp.txt, this temp.txt is overwritten. i want to get the output files as same sql file name. – kevin May 04 '17 at 06:22
  • @vijeth: good work man . i was thinking of doing one by one some 200 sql files. saved a lot of time – Uthistran Selvaraj Jul 05 '17 at 06:14
  • @Vijeth thank you. i just modify for myself : REM REM development environment only!! REM pause for %%G in (*.sql) do sqlcmd /S "192.168.10.139\SQLEXPRESS" /d "TESTDEV_DB" -U "atiour" -P "atiour" -i"%%G" pause REM REM All Script Run Successfully REM – Mohammad Atiour Islam Jul 14 '17 at 12:39
  • If you are not getting any results by double clicking, try opening Command Prompt as Administrator go to the folder and run the bat file. – live-love Aug 28 '19 at 14:34
  • How to give the full path where .Sql files present not only drive path. Please let me know. – Sudhanshu Pal Apr 19 '22 at 04:48
74

Use FOR. From the command prompt:

c:\>for %f in (*.sql) do sqlcmd /S <servername> /d <dbname> /E /i "%f"
Tao
  • 13,457
  • 7
  • 65
  • 76
Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
  • 2
    I had to add quotes around the last "%f" to make it work with scripts that contain spaces – Steve Wright Jun 28 '11 at 20:51
  • For a version that works in batch files, see [this answer](http://stackoverflow.com/a/6504317/70345). – Ian Kemp Aug 06 '13 at 12:10
  • I also had to add some other params (e.g. /I to enable quoted identifiers) – Pavel K Sep 04 '14 at 11:22
  • i like this one - but is there any way to have the results output to a file? so i can easily see any exceptions? i just tried this command on 136 .sql files, so i've lost visibility of most of them – Rich Aug 31 '16 at 20:26
  • 2
    @Rich To redirect output to file, use this command: `for %f in (*.sql) do sqlcmd /S /d /E /i "%f" >> sql.log 2>&1)` You can read more about redirection of output [here](http://www.robvanderwoude.com/battech_redirection.php) – danijelk Sep 01 '16 at 15:23
37

The easiest way I found included the following steps (the only requirement is it to be in Win7+):

  • open the folder in Explorer
  • select all script files
  • press Shift
  • right click the selection and select "Copy as path"
  • go to SQL Server Management Studio
  • create a new query
  • Query Menu, "SQLCMD mode"
  • paste the list, then Ctrl+H, replace '"C:' (or whatever the drive letter) with ':r "C:' (i.e. prefix the lines with ':r ')
  • run the query

It sounds long, but in reality is very fast (it sounds long as I described even the smallest steps).

buddemat
  • 4,552
  • 14
  • 29
  • 49
PepiX
  • 479
  • 5
  • 4
  • 1
    It's an amazingly fast way! – jaczjill Sep 12 '20 at 05:37
  • This was a fast and easy way. Good tip! But I had to either remove or add the '\' in the replace bullet. – Radiopepper Sep 21 '21 at 14:36
  • it's a life saver.. – Gurmeet Feb 15 '22 at 15:50
  • What about stored procedures? Is there a similar way to run SPs? – Suyash Gupta Aug 30 '22 at 16:06
  • we need to remove and replace the double quote with space too – adumred Jan 11 '23 at 11:19
  • In fact no.. we shouldn't remove the double quotes.. You would get 'Incorrect syntax was encountered while parsing :r .' if you remove the quotes. – PepiX Jan 12 '23 at 12:28
  • This is good, just need to double check the order, I find it's never the same as the order or the files for whatever reason – Dave Jul 19 '23 at 02:54
  • @SuyashGupta sqlcmd can run any file. if your sp is scripted, you can run it. This is an good poor mans change control. you have to maintain the files of course, but you can run multiple files to a testDB, test the changes, then run the same changes to prod and be confident the same thing happened. – greg Jul 19 '23 at 13:09
36
  1. In the SQL Management Studio open a new query and type all files as below

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
    
  2. Go to Query menu on SQL Management Studio and make sure SQLCMD Mode is enabled
  3. Click on SQLCMD Mode; files will be selected in grey as below

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
    
  4. Now execute
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Ramakrishna Talla
  • 1,011
  • 12
  • 7
  • 4
    this is really tedious if I have hundreds of files. – devlin carnate Nov 18 '17 at 03:36
  • 1
    @devlincarnate: Presumably you can come up with a way to automate step 1. Such as "dir /B *.sql > list.txt", and then massage that list.txt file a bit. – Jeff Roe Aug 17 '18 at 19:05
  • 4
    @devlincarnate in newer versions of Windows, you can hold down the Shift key, right-click a file, and select "Copy as path". From there, CTRL+V into an SSMS window. It works with multiple files too. Select two or more files in Explorer, right-click any of the highlighted files, and select "Copy as path". Repeat steps in SSMS. File paths are enclosed in double-quotes, which you may or may not want to strip out in SSMS with Find/Replace. – Dave Mason Sep 26 '18 at 19:15
25

Make sure you have SQLCMD enabled by clicking on the Query > SQLCMD mode option in the management studio.

  1. Suppose you have four .sql files (script1.sql,script2.sql,script3.sql,script4.sql) in a folder c:\scripts.

  2. Create a main script file (Main.sql) with the following:

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
    :r c:\Scripts\script4.sql
    

    Save the Main.sql in c:\scripts itself.

  3. Create a batch file named ExecuteScripts.bat with the following:

    SQLCMD -E -d<YourDatabaseName> -ic:\Scripts\Main.sql
    PAUSE
    

    Remember to replace <YourDatabaseName> with the database you want to execute your scripts. For example, if the database is "Employee", the command would be the following:

    SQLCMD -E -dEmployee -ic:\Scripts\Main.sql
    PAUSE
    
  4. Execute the batch file by double clicking the same.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
  • I just edited my answer. Also, one needs to make sure the script files exist in the specified path. – Ashish Gupta Apr 06 '10 at 10:34
  • 1
    the good thing about this approach is that any error is found then stop executing further scripts :) similar to `-b` example: `SQLCMD -b -i "file 1.sql","file 2.sql"` – Jaider Sep 05 '14 at 17:03
  • and the bad thing about this approach that one has to maintain the list of all SQL files to be ran. – Francisco d'Anconia Oct 03 '17 at 18:09
10

General Query

save the below lines in notepad with name batch.bat and place inside the folder where all your script file are there

 for %%G in (*.sql) do sqlcmd /S servername /d databasename  -i"%%G"
    pause

EXAMPLE

for %%G in (*.sql) do sqlcmd /S NFGDDD23432 /d EMPLYEEDB -i"%%G" pause

sometime if login failed for you please use the below code with username and password

for %%G in (*.sql) do sqlcmd /S SERVERNAME /d DBNAME -U USERNAME -P PASSWORD -i"%%G"
pause

for %%G in (*.sql) do sqlcmd /S NE8148server /d EMPLYEEDB -U Scott -P tiger -i"%%G" pause

After you create the bat file inside the folder in which your Script files are there just click on the bat file your scripts will get executed

Lijo
  • 6,498
  • 5
  • 49
  • 60
9

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

Kevin L
  • 99
  • 1
  • 5
5

I wrote an open source utility in C# that allows you to drag and drop many SQL files and start running them against a database.

The utility has the following features:

  • Drag And Drop script files
  • Run a directory of script files
  • Sql Script out put messages during execution
  • Script passed or failed that are colored green and red (yellow for running)
  • Stop on error option
  • Open script on error option
  • Run report with time taken for each script
  • Total duration time
  • Test DB connection
  • Asynchronus
  • .Net 4 & tested with SQL 2008
  • Single exe file
  • Kill connection at anytime
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Clinton Ward
  • 2,441
  • 1
  • 22
  • 26
3

What I know you can use the osql or sqlcmd commands to execute multiple sql files. The drawback is that you will have to create a script for both the commands.

Using SQLCMD to Execute Multiple SQL Server Scripts

OSQL (This is for sql server 2000)

http://msdn.microsoft.com/en-us/library/aa213087(v=SQL.80).aspx

A G
  • 21,087
  • 11
  • 87
  • 112
2
@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE

for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a
)

Step1: above lines copy into note pad save it as bat.

step2: In d drive abc folder in all Sql files in queries executed in sql server.

step3: Give your ip, user id and password.

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
1

I know this question is more focused on SQL Server. I had the same question, but for PostgreSQL. The solution is very close for what I needed, so I thought I would share what I got for anyone that needs it:

for %f in (*.sql) do psql -U [username] -d [database name] --command="\i %f";

I ran this from the folder containing all of my sql scripts.

To avoid being prompted for a password, I had to add

*:*:*:[user]:[password]

to my pgpass.conf file that lives in

%APPDATA%\Roaming\postgresql\ 

folder on windows. I had to create the file myself.

Gabriel Kunkel
  • 2,643
  • 5
  • 25
  • 47
0

You can create a single script that calls all the others.

Put the following into a batch file:

@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"

When you run that batch file it will create a new script named all.sql in the same directory where the batch file is located. It will look for all files with the extension .sql in the same directory where the batch file is located.

You can then run all scripts by using sqlplus user/pwd @all.sql (or extend the batch file to call sqlplus after creating the all.sql script)

lucian.pantelimon
  • 3,673
  • 4
  • 29
  • 46
rahul jain
  • 143
  • 1
  • 3
  • 12
0

For executing every SQLfile on the same directory use the following command:

ls | awk '{print "@"$0}' > all.sql

This command will create a single SQL file with the names of every SQL file in the directory appended by "@".

After the all.sql is created simply execute all.sql with SQLPlus, this will execute every sql file in the all.sql.

jww
  • 97,681
  • 90
  • 411
  • 885
0

If you can use Interactive SQL:

1 - Create a .BAT file with this code:

@ECHO OFF ECHO
for %%G in (*.sql) do dbisql -c "uid=dba;pwd=XXXXXXXX;ServerName=INSERT-DB-NAME-HERE" %%G
pause

2 - Change the pwd and ServerName.

3 - Put the .BAT file in the folder that contains .SQL files and run it.