SQLCMD Usage in Batch file - sql-server-2005

Hi All I am Writing a Batch Script Which has to read a set of SQL Files which exists in a Folder then Execute Them Using SQLCMD utiliy.
When I am Trying to execute it does not create any output file. I am not sure where I am wrong and I am not sure how to debug the script. Can someone help me out with script?
#echo off
FOR %F IN (C:\SQLCMD*.SQL) DO sqlcmd -S LENOVO-C00 -U yam -P yam!# -i %F -o C:\SEL.txt -p -b
IF NOT [%ERRORLEVEL%] ==[0] goto get_Error
:Success echo Finished Succesffuly exit /B 0 goto end
:get_error echo step Failed exit /B 40
:end

If this is actually in a batch file (not being executed by hand at the command line), then the %F variables need to have the % characters doubled-up because of the way that cmd.exe executes the lines read from the batch file:
FOR %%F IN (C:\SQLCMD*.SQL) DO sqlcmd -S LENOVO-C00 -U yam -P yam!# -i %%F -o C:\SEL.txt -p -b
Though I would have thought you'd get a
F was unexpected at this time.
error if you only had one % character in front of the variable name.

Try to right click the Batch File and run as administrator.

Seems like the answer would be more like this:
FOR %%F "usebackq" IN (`dir.exe C:\SQLCMD*.SQL`) DO ...

Related

How to get error name in batch when I use OSQL command?

I created a batch file which execute a sql command.
Let's see the piece of code
SET OSQL="C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Binn\osql.exe"
IF NOT EXIST %OSQL% ECHO OSQL.EXE not found, please check the OSQL variable!
IF NOT EXIST %OSQL% GOTO :ERROR
SET SQLQUERY_UPDATEDB = "SELECT * FROM %DB%";
%OSQL% -S %SQLSERVERNAME% -d %DBNAME% -U %DBACCOUNT% -P %DBPASSWORD% -Q %SQLQUERY_UPDATEDB% -n -b -m-1 > D:\sqloutput.txt
:ERROR
ECHO Sorry, could not complete your request!
ECHO %ERRORLEVEL%
GOTO :END
:END
ECHO Finish batch
The above part of code returns always 0 and Sorry, could not complete your request! . What does mean ?
How to set up to display error in console to see exactly what does wrong ?
I put -m-1 and I removed -h-1 accordingly with MSDN but doesn't show up in my console.
Thank you.
Um. Because even if it runs the SQL Command successfully, it then drops into the error handler?
Try adding a GOTO :END after you run the command:
SET SQLQUERY_UPDATEDB = "SELECT * FROM %DB%";
%OSQL% -S %SQLSERVERNAME% -d %DBNAME% -U %DBACCOUNT% -P %DBPASSWORD% -Q %SQLQUERY_UPDATEDB% -n -b -m-1 > D:\sqloutput.txt
GOTO :END
:ERROR

Exclude files that start with number - batch script

How to exclude the files from the loop -> if the file name in a directory starts with number.
for %%G in (*.sql) do sqlcmd -S %SName% -U %UName% -P %Pwd% -d %DbName% -Q "EXECUTE sp_deploy %%~nG" >> "C:\%%~nG.sql" 2>&1
I do not want to execute the sql if the file name start with a number. How can I stop that..
Thanks in advance.
"if '%%~nG' not like '[0-9]%' EXECUTE sp_deploy %%~nG"

Can I specify an input sql file with bcp?

How can I specify an input sql file with a long query when using bcp? I tried using the -i option but it keeps complaining about a command-line error with no extra information. Is this possible?
I had this problem today and found a convenient workaround, at least in an ad-hoc situation.
Temporary tables can be created by any user with connect permissions. This means you can also create GLOBAL temporary tables.
Just run your query in enterprise manager (or sql cmd or whatever) using SELECT ...INTO with a global temporary table e.g.
SELECT *
INTO ##mytemptable
FROM SomeTable
WHERE [massive where clause, for example]
You can then use the temporary table in the BCP query with a simple
SELECT * FROM ##mytemptable
Then drop the temp table through enterprise manager
DROP TABLE ##mytemptable
I did other way for fix that.
I create a batch file which read a file and send your content in bcp command. See:
#ECHO off
SETLOCAL EnableDelayedExpansion
SET queryFile=%1
SET outFileName=%2
FOR /F "delims=" %%i IN (%queryFile%) DO SET join=!join! %%i
ECHO %join%
bcp "%join%" queryout %outFileName% /S.\SQLE_CAESAR /d /c /t"|" /T
That script receive two parameters:
Filename which has a query;
Filename for export data;
Execute a script in cmd like that:
export-query.bat query.sql export.txt
I hope helped.
As far as I'm concerned the BCP utility only supports Transact-SQL queries directly written to the command line. Ex:
bcp "SELECT Name FROM AdventureWorks.Sales.Currency" queryout Currency.Name.dat -T -c
According to its reference the "-i" option:
Specifies the name of a response file, containing the responses to the command prompt questions for each data field when a bulk copy is being performed using interactive mode (-n, -c, -w, or -N not specified).
Notice that it differs from the sqlcmd Utility "-i" option:
Identifies the file that contains a batch of SQL statements or stored procedures. Multiple files may be specified that will be read and processed in order (...)
try :
query=$( cat < /file.sql )
export query
bcp "${query}" queryout /home/file.csv
Multi-line queries can be given to bcp easily using powershell:
PS> $query = #'
select *
from <table>
'#
PS> bcp $query queryout <outfile> -d <database> -T -S <server> -c
I had face same issue, may not be a very good approach. However, I did something like the following
bcp "declare #query nvarchar(max) set #query = (SELECT * FROM OPENROWSET(BULK 'F:\tasks\report_v2.sql', SINGLE_CLOB) AS Contents) exec sp_executesql #query" queryout %outFileName% /c /C RAW -S . -U sa -P 123 -d blog /T
And I must say, if you use like global temp table then global temp table is dropped itself of after query executed. you can't use this at some situations
What really worked for me is this:
#ECHO off
setlocal enableextensions enabledelayedexpansion
SET "queryFile=%1"
SET "outFileName=%2"
SET RESULT=
FOR /F "delims=" %%i IN ('type %queryFile%') DO SET RESULT=!RESULT! %%i
echo %RESULT%
rem bcp "%RESULT%" queryout %outFileName% -t^ -r \n -T -k -c -d DB_NAME -S SERVER_NAME
type file is the equivalent of cat file in unix
What I did with complex queries was create a stored procedure with the desired statement and call it from BCP:
bcp "exec db.schema.stored_procedure" queryout "c:\file.txt" -T -S localhost -t "|" -c
This worked great for me. Greetings!
I made my own script (called of bulk.sh) to do this (not optimal and not best practice... The script is too ugly, but very functional).
#!/bin/bash
input="SQL_FILE.sql"
count=0
const=1000
lines=()
mkdir -p bulk
while IFS= read -r line
do
lines+=("$line")
count=$((count+1))
check=$((count % const))
if [[ $check -eq 0 ]]; then
bulk="${lines[*]}"
unset lines
number=$(printf "%010d" $count)
echo $bulk > "bulk/bulk${number}.sql"
bulk=""
fi
done < "$input"
FILES="bulk/*"
for f in $FILES
do
echo "Processing $f file..."
sqlcmd -S SERVER -d DATABASE -U USER -P "PASSWORD" -i "$f"
sleep 2s
done
You can try it, with:
$ docker run -v /path/to/your/sql/file/folder:/backup -it mcr.microsoft.com/mssql-tools
$ bash bulk.sh

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.

DOS command to execute all SQL script in a directory and subdirectories

I need a DOS command or a batch (.bat) file I can execute to run all the *.sql scripts in a directory and its subdirectories. What would the solution be?
The following will get you started
for /r %f in (*.sql) do echo %f
Run from the command line that will print the names of all the SQL files in the current directory and all sub directories.
Then substitute sqlcmd <connection args> -i%f for echo %f to execute the scripts.
Hope this helps.
Here you go. This batch file will execute all sql files in a directory and its subdirectories. It will also create an output.txt file with the results so you can see errors and whatnot. Some notes on batch file:
[YourDatabase] is the name of the database you want to execute the scripts against.
[YourPath] is the path of where you keep all the scripts.
[YourServerName\YourInstanceName] is the SQL server name and instance name, separated with a '\'
You'll want to replace the text after the '=' for each variable with whatever is appropriate for your server
Be sure NOT to put spaces around the '='
Do not put any quotes around [YourPath]
Make sure that [YourPath] has a '\' at the end
SET Database=[YourDatabase]
SET ScriptsPath=[YourPath]
SET ServerInstance=[YourServerName\YourInstanceName]
IF EXIST "%ScriptsPath%output.txt" del "%ScriptsPath%output.txt"
type NUL > "%ScriptsPath%output.txt"
FOR /R "%ScriptsPath%" %%G IN (*.sql) DO (
sqlcmd -d %Database% -S %ServerInstance% -i "%%G" -o "%%G.txt"
echo ..................................................................................... >> "%ScriptsPath%output.txt"
echo Executing: "%%G" >> "%ScriptsPath%output.txt"
echo ..................................................................................... >> "%ScriptsPath%output.txt"
copy "%ScriptsPath%output.txt"+"%%G.txt" "%ScriptsPath%output.txt"
del "%%G.txt"
)
for %f in ("c:\path\to\dir\*.sql") do sqlcmd -S [SERVER_NAME] -d [DATABASE_NAME] -i "%f" -b
Try a for loop. The options of this command have evolved and I'm not sure what version of DOS you are using, but assuming that DOS includes "cmd.exe from Windows XP", something like this could work:
for /r . %f in (*.sql) do #echo %f
Ok, this will only print the names of the files. I'm assuming you already have a program that you can run from the command line that will execute one SQL file, which you can use instead of echo.
For more information, try for /?.