Run all SQL files in a directory - sql

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?

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!

Use FOR. From the command prompt:
c:\>for %f in (*.sql) do sqlcmd /S <servername> /d <dbname> /E /i "%f"

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
Go to Query menu on SQL Management Studio and make sure SQLCMD Mode is enabled
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
Now execute

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).

Make sure you have SQLCMD enabled by clicking on the Query > SQLCMD mode option in the management studio.
Suppose you have four .sql files (script1.sql,script2.sql,script3.sql,script4.sql) in a folder c:\scripts.
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.
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
Execute the batch file by double clicking the same.

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

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):
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:

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

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

#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.

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.

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)

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.

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.

Related

Sequential Running of Scripts in SQL Server (without using a batch file)

I have 30 scripts of SQL code that I have been told to execute one by one (in a certain order) within SQL Server.
I am unable to use a batch file to do so (for reasons out of my control) and from another Question/Answer on this site I believe I can do something like the following:
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
Go to Query menu on SQL Management Studio and make sure SQLCMD Mode is enabled
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
Now execute
My problem is my files have whitespace in their names for example:
'7. Address and Phone Number.sql'
I have been toying around with it trying to get the above method to work to no avail, any help would be greatly appreciated.
Consider most any programming language (Java, C#, C++, Python, PHP, VB) to iterate through scripts in file directory and call sqlcmd at command line. Recall sqlcmd is a separate executable tool with MSSQL installations, allowing command line interfacing to SQL Server (apart from IDEs like SSMS) and is available in both Windows and Linux installations.
Specifically, follow how to Run Transact-SQL Script Files. For batch jobs, use command line interpreters like Window's PowerShell and Unix's Bash.
PowerShell (save as .ps1 and run in PS ISE or PS terminal)
Get-ChildItem "C:\Scripts" -Filter *.sql |
Foreach-Object {
Write-Host $_.FullName
Start-Process -FilePath "sqlcmd" -S myServer\instanceName -i $_.FullName
# Invoke-Expression "& sqlcmd -S myServer\instanceName -i $_.FullName"
}
Bash (save as .sh and run in IDE or terminal)
#!/bin/bash
for file in C:/Scripts/*.sql; do
[ -e "$file" ] || continue
./sqlcmd -S myServer\instanceName -i "$file"
done

batch file for executing sql query in a production server

is it possible to create a batch file which run from local computer to execute a query in production server, production server can be accessible only through remote connection. ? if not possible please suggest some ways,
Requirement: Need a batch files to get query results from production server?
Try like this,
Step-1:
Enter the below five lines and Save this as execute.bat file
set /P TargetServer=Enter Target DB Server IP:
set /P TargetDb=Enter Target DB Name:
set /P UserName=Enter UserName:
set /P Passwd=Enter Password:
sqlcmd -S %TargetServer% -U %UserName% -P %Passwd% -d %TargetDb% -i MyScript.sql -o MyOutput.txt
Step-2
Provide your sqls in this file and save it as MyScript.sql
select *from tablename
Step-3
Place execute.bat and Myscript.sql files in a folder then double click the execute.bat file. Your output of the MyScript.sql is saved in MyOutput.txt file.
Create a Batch file and Keep it production server itself by scheduling a task Task Scheduler (Windows assumed OS). So that no need of Remote access to Production server every time.
This is my suggestion from what I understood from your question.

Calling one sql file from another

Is there an easy way to call one sql file from another?
We have 2 sql files - a.sql and b.sql for our products. Locally we create the db's A and B and then run a.sql an b.sql.
Now, there is another team that has been maintaining an sql file MasterFile.sql which is supposed to create all the dbs needed for this project and configure them. We now need to ensure that the contents of our sql files (a.sql and b.sql) are also called from this masterFile.sql.
Both a.sql and b.sql are subject to change in the near future and therefore we dont want to manually add the contents to MAsterFile.sql.
What is the best way to do this? I tried doing sqlcmd as well as source and :r a.sql, but none of them worked.
How about using a batch file with 3 lines
sqlcmd /S servername /d databaseName /E /i "master.sql"
sqlcmd /S servername /d databaseName /E /i "a.sql"
sqlcmd /S servername /d databaseName /E /i "b.sql"
You can use xp_cmdshell and sqlcmd, as explained in this question:
Is it possible to execute a text file from SQL query?

How to run multiple SQL scripts using a batch file?

I have a case where i have got 10+ SQL script.
I don't want to go and run all my scripts 1 by 1.
Is there a way that i can run all my scripts in succession in SQL Management studio.
I found this post. Creating a batch file seems easier.
This is all you need:
#echo off
ECHO %USERNAME% started the batch process at %TIME% >output.txt
for %%f in (*.sql) do (
(
sqlcmd.exe -S servername -E -d databasename -i %%f >>output.txt
)
pause
Replacing servername and databasename, but it seems to be not working.
Any ideas?
You've got an unmatched parenthesis, there.
Try
for %%f in (*.sql) do sqlcmd.exe -S servername -E -d databasename -i %%f >>output.txt
I just saved it in a .cmd file and it appears to be working.
Yes, it's possible. You can do it with :r command of SQLCMD.
I strongly recommend you to read this article and do it with SQLCMD
http://www.mssqltips.com/sqlservertip/1543/using-sqlcmd-to-execute-multiple-sql-server-scripts/
You can create a Strored Procedure to call all your Scripts. You could also create a schedule plan to run the scripts automaticaly.
http://msdn.microsoft.com/en-us/library/aa174792(v=sql.80).aspx
Here is an open source utility with source code http://scriptzrunner.codeplex.com/
This utility was written in c# and allows you to drag and drop many sql files and start running them against a database.
You can use Batch Compiler add-in for SMSS, it let's you run multiple scripts at once, create SQLCMD scripts or consolidate them into a *.sql file.
Some batch trick
cd %~dp0 //use this if you use 'for xxx in', it solved most of my problems
ECHO %USERNAME% started the batch process at %TIME% >output.txt
for %%f in (*.sql) do (
(
sqlcmd.exe -S servername -E -d databasename -i %%f >>output.txt
)
echo %errorlevel%
pause
If you want to run Oracle SQL files through a Batch program, then the code below will be useful. Just copy & change the Database credential and DB names
#echo off
for %%i in ("%~dp0"*.sql) do echo #"%%~fi" >> "%~dp0all.sql"
echo exit | sqlplus scott/tiger#orcl #"c:\users\all.sql"
pause
Basically, you need to put this batch file in the folder where you have all the SQL files. It will first get all the sql file names in the directory and load their full path with the sql file names. Then, it will write into a file all.sql and then sqlplus will call that all.sql to execute all the sql files that you have in that directory.

Need help to write bat file that execute sql scripts in (sql server 2008 and another 3 files.?

I am sure these has been asked before but cannot find clear instruction how to create a
batch file lets call it "Update Database" this batch file should
Execute sql scripts located in different folders
Execute another 3 bat files.
Any quick examples how to do it?Never done it before
thanks a lot
EDITED
Can I do this?
:On Error exit
:r C:\myPath\MasterUpdateDatabase.bat
GO
SQLCMD -S (Local) -i C:\myPath\InsertUsername.sql
I get an error:
"GO" is not recognized as internal external command
Thanks for any input
It looks like you're trying to use DOS commands to create a batch file that either (a) executes other batch files or (b) executes SQLCMD to run sql or a sql script.
Here are a couple examples all rolled into one. I'm using the DOS command START with the /WAIT switch, which will keep your original "master" batch file running in one window and execute the subsequent file or commands in a new window. That new window stays open until the script finished AND exits.
Some of the ECHOs probably aren't required, but the script will talk back to you for now, a little.
#echo off
So, this is pretty simple in the sense that you're just running the script. If you're script1.bat has break points, you can return an error back to the main script and have it end immediately. I wasn't clear if that was what you needed the master script to do.
echo Starting Database Update.
echo.
echo Excuting Script 1
echo.
start /wait C:\path\to\your\script1.bat
echo If there was a problem, break here.
Pause
echo Excuting Script 2
echo.
start /wait C:\path\to\your\script2.bat
echo If there was a problem, break here.
Pause
Here is where did used the same START /WAIT to run SQLCMD, which in this case just returns results from the query. One thing to note here is that the -Q (uppercase) runs the query and quits. If you use -q (lowercase) it will run the query and sit open in SQLCMD waiting for another query.
echo.
echo Running SQLCMD: "select top 100 * from sys.objects"
start /wait sqlcmd -S (local) -Q "select top 100 * from sys.objects"
And this is how you can run a sql script, which is what the -i denotes, but I also didn't run this in the START /WAIT as earlier. Not that you have to, but I wanted to show both examples. What this also shows is the -b will end the batch process if your script returns an error, which is useful if you're running multiple scripts that depend on success of the former(s).
echo.
echo Running SQLCMD from an (-i)nput file:
sqlcmd -S (local) -i C:\path\to\your\script.sql -b
echo.
echo Update Complete.
pause
End
So, I assumed you were looking for a .bat or .cmd file that utilized SQLCMD. The example I provided is pretty basic, but hopefully it sets you on the right path.
OH! And remember that CTRL+C breaks a batch script in process.
The actual error you're seeing is that the command line interpreter does not recognize 'GO', so you could just remove that line.
Hope this helps you :
sqlplus UserName/Password#DataBase #C:\myPath\InsertUsername.sql
P.S : Don't forget to add the command "commit;" at the end of sql file (InsertUsername.sql), this command order Oracle to save performed changes in darabase
This answer definitely works for your purposes:
sqlcmd -S localhost -U fdmsusr -P fdmsamho -i "E:\brantst\BranchAtt.sql" -o "E:\brantst\branchlog.txt"