Way of executing several .sql files at once in SQL Server - sql

I have around 100 .sql files that create stored procs. I'd like to execute them at once all of them.
They are contained inside a folder called Stored Procedures. There several other folders with different names --Table names-- inside the Stored Procedures folder.
Is there a way to execute all these files at once?

You could open up a PowerShell instance and run a command like the following:
Get-ChildItem ".\Stored Procedures\*.sql" | ForEach-Object { sqlcmd -S ServerName -d DatabaseName -E -i $_.FullName }
This will get each .sql file in the Stored Procedures directory, and one by one, pass it to the sqlcmd.exe program. To get more details on the parameters for sqlcmd you can run sqlcmd /?.
To make it recursive through sub directories, you can apply the -Recurse parameter to Get-ChildItem along with the -Filter parameter:
Get-ChildItem '.\Stored Procedures' -Filter *.sql -Recurse | ForEach-Object { sqlcmd -S ServerName -d DatabaseName -E -i $_.FullName }

Here is the another tool Sql_Server_Script_Executor
Is there a way to execute all these
files at once?
*You can add folder and all your files will comes up in the list. Click the execute button and done!!!!!!!!!!!!! *
It contains three transaction modes.
1. Execute scripts within one transaction
2. Execute scripts on separate transaction
3. No transaction
and many more features please go through it.

Not at once - but all in one go - try a tool like the SSW Deploy one.

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

How to run all postgres sql scripts from same folder using shell script

How do i write a shell script that runs postgres sql scripts stored in one folder sequentially.Example
1)dump.sql,
2)store.sql,
3)merge.sql,
4)import.sql
are to run sequentially in the same order and all the scripts are in the same folder. How do i write a shell script that performs the tasks sequentially.
Inside psql you can use "\i " to load a script. But also "\ir ".
So in your case create a load-all.sql file in the same directory as your other files..
contents load-all.sql:
\ir dump.sql
\ir store.sql
\ir merge.sql
\ir import.sql
inside psql:
psql# \i /path/to/file/load-all.sql
You can create a simple script e.g run.sh and the define variables corresponding to your environment. Here is a simple script that is running 2 sql files which are present on Desktop
PG_HOME=/usr/pgsql-12
PGUSER=postgres
DATABASE=postgres
PORT=5432
FILES_HOME=/home/edb/Desktop
$PG_HOME/bin/psql -U $PGUSER -d $DATABASE -p $PORT -f $FILES_HOME/dump.sql
$PG_HOME/bin/psql -U $PGUSER -d $DATABASE -p $PORT -f $FILES_HOME/store.sql
There are database schema migration tools available to help manage this process.
Examples include:
Flyway
Liquibase
I use Flyway. It does exactly what you want, connects to the database and runs a bunch of SQL scripts found in a folder. The order of execution is determined by the file names named using a certain convention.
On the first run, Flyway adds its own table to your database to store the history of what SQL scripts have been run. On subsequent runs, Flyway knows what SQL scripts have already been applied (and should be skipped) and which scripts are fresh (and should be applied).
Try this:
param([string]$directory = "")
$files = Get-ChildItem $directory
for ($i=0; $i -lt $files.Count; $i++) {
$scriptName = $files[$i].Name
psql -U <username> -d <database> -h <host> -p <port> -f $directory\$scriptName
}
directory is an argument you should pass to the script.
So executing it with:
./sqlScript.ps1 C:\Users\<username>\Desktop\<pathToDict>
If you are troubling with executing psql on windows environment you can get help with
this:
How to start psql.exe

How to execute the SQL Script through Batch Script Command from SQL?

I am trying to execute the .sql file from batch script, but not able to execute.
Script has multiple scripts such as Create Table , Stored Procedure separated by GO statement.
I tried with the below script, however script was not executed.
DB Servername : localhost\SQL2017
Authentication : Windows
sqlcmd -E -S localhost\SQL2017\MyDatabase -i C:\SQLScripts\TestScript.sql
Try this instead:
sqlcmd -E -S localhost\SQL2017 -d MyDatabase -i C:\SQLScripts\TestScript.sql
You need to use the -d parameter to specify the database name. The -S parameter should contain only the server name and the instance.

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.

Run all SQL files in a directory

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.