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

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"

Related

Unable to run a postgresql script from bash

I am learning the shell language. I have creating a shell script whose function is to login into the DB and run a .sql file. Following are the contents of the script -
#!/bin/bash
set -x
echo "Login to postgres user for autoqa_rpt_production"
$DB_PATH -U $POSTGRESS_USER $Auto_rpt_production$TARGET_DB -p $TARGET_PORT
echo "Running SQL Dump - auto_qa_db_sync"
\\i auto_qa_db_sync.sql
After running the above script, I get the following error
./autoqa_script.sh: 39: ./autoqa_script.sh: /i: not found
Following one article, I tried reversing the slash but it didn't worked.
I don't understand why this is happening. Because when I try manually running the sql file, it works properly. Can anyone help?
#!/bin/bash
set -x
echo "Login to postgres user for autoqa_rpt_production and run script"
$DB_PATH -U $POSTGRESS_USER $Auto_rpt_production$TARGET_DB -p $TARGET_PORT -f auto_qa_db_sync.sql
The lines you put in a shell script are (moreless, let's say so for now) equivalent to what you would put right to the Bash prompt (the one ending with '$' or '#' if you're a root). When you execute a script (a list of commands), one command will be run after the previous terminates.
What you wanted to do is to run the client and issue a "\i ./autoqa_script.sh" comand in it.
What you did was to run the client, and after the client terminated, issue that command in Bash.
You should read about Bash pipelines - these are the way to run programs and input text inside them. Following your original idea to solving the problem, you'd write something like:
echo '\i auto_qa_db_sync.sql' | $DB_PATH -U $POSTGRESS_USER $Auto_rpt_production$TARGET_DB -p $TARGET_PORT
Hope that helps to understand.

Executing series of SQL commands on the command line

I want to run a series of SQL statements against a SQL Server 2005 database from the command line.
When I launch 1st statement
osql -E -S <Server_Name>\<Instance_Name> -d <Server_Name>
it is going to prompt window 1> from there after I am unable to proceed further through script.
How to give input to 1> prompt I mean giving next SQL statement
BACKUP DATABASE TO DISK = 'c:\test.bak' WITH INIT,SKIP
and finally exit to that prompt
I tried with && but I guess that is for only commandline commands.
You ae looking for the -Q switch on the sqlcmd tool (don't use osql on sqlserver 2005 or higher) (type sqlcmd /? to see all options) or lookit up on msdn
sqlcmd -E -S <Server_Name>\<Instance_Name> -d <Server_Name> -Q "BACKUP DATABASE TO DISK = 'c:\test.bak' WITH INIT,SKIP"
Alternatively you can create a sqlscript file where you put all the sql statements in you want to execute. Assuming you name your file myscript.sql the osql command would go like this:
sqlcmd -E -S <Server_Name>\<Instance_Name> -d <Server_Name> -i myscript.sql
Perhaps you may want to try a small trick that emerged from other question in this forum (that was deleted unfortunately).
You may insert the input for a command directly in the lines below the command and then execute the file NOT as Batch file, but as input por cmd.exe (this is similar to a here document in Linux). For example:
script.TXT:
#echo off
osql -E -S <Server_Name>\<Instance_Name> -d <Server_Name>
BACKUP DATABASE TO DISK = 'c:\test.bak' WITH INIT,SKIP
exit
Execute previous "script" this way:
cmd < script.TXT
If you perform this test, please report the result...
Antonio

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.

sqlcmd runs script but script does not affect database

So we have a .bat file that runs SQL scripts, e.g.
#ECHO --- 03_Case6395_Publication.sql --- >> dbupt.log
sqlcmd -U %1 -P %2 -S %3 -d %4 -i 03_Case6395_Publication.sql -k -b >> dbupt.log
IF ERRORLEVEL 1 GOTO ErrorTag
The script runs and gives no errors, but the script doesn't actually affect the database. In the example above, here is what is being run:
IF NOT EXISTS (SELECT 1 FROM [dbo].[syscolumns] WHERE [NAME] = N'MandatoryInList' AND [ID] = object_id(N'Pub_Type'))
BEGIN
ALTER TABLE [dbo].[Pub_Type] ADD [MandatoryInList] bit NULL CONSTRAINT [DF_PubType_MandatoryInList] DEFAULT (0)
END
ELSE
BEGIN
ALTER TABLE [dbo].[Pub_Type] ALTER COLUMN [MandatoryInList] bit NULL
END
GO
The script is pretty simple and you would expect it to add a column called MandatoryInList, however it doesn't. The odd thing is there are no syntax errors in the script and when I run it from SQL Server Management Studio, it runs fine. There's no issues with permissions or which user is running the script because there are other scripts that run fine in the batch file.
I should also mention that this runs from a GUI by creating a new process and running it but not showing the command window. But regardless, I've been running the tool like this for months without any issues.
Any ideas?
So it works from Management Studio but not from your batch file that calls sqlcmd. Strange...
I don't know what could cause this, but here are some ideas:
If you run the same "sqlcmd" command manually from the command prompt, rather than from your batch file, does it work?
If you run the batch file from the command prompt, rather than invoking it from the GUI app, does it work?
What's it writing to your dbupt.log file? Does it have the header "--- 03_Case6395_Publication.sql --- ", and it's empty after that?
Can you add some PRINT statements to the script, so you can see whether it's executing the IF or the ELSE part?
Can you try redirecting the error stream to your log file as well, using the "2>&1" operator? E.g.:
sqlcmd -U %1 -P %2 -S %3 -d %4 -i 03_Case6395_Publication.sql -k -b >> dbupt.log 2>&1
Can you try changing "IF ERRORLEVEL 1" to "IF NOT ERRORLEVEL 0"?
Have you tried using SQL Profiler to see what SQL is actually executing? Does anything show up?