using a While Loop in batch file with sql - sql-server

I am new to Batch.
My code:
#ECHO OFF
SET colu=
SET sn=
SET /P colu= Enter column name:
SET /P sn= Enter ID :
sqlcmd -U USER -P PWORD -S SERVER -d DBNAME-i sqlSCRIPT.sql -o LOG.txt -v delete=%colu% d_id=%%I
pause
SET /P sn= Enter ID :
sqlcmd -U USER -P PWORD -S SERVER -d DBNAME-i sqlSCRIPT.sql -o LOG.txt -v delete=%colu% d_id=%%I
pause
SET /P sn= Enter ID :
sqlcmd -U USER -P PWORD -S SERVER -d DBNAME-i sqlSCRIPT.sql -o LOG.txt -v delete=%colu% d_id=%%I
The code works and does what I need it to do which is delete records from the db but I was hoping that there was a more efficient way to write it.
How would I implement a while loop in batch that will keep asking the user to enter the id until they press the end key? Also I realize that having pause in between sqlcmd is highly inconvenient.

How about something like this:
#ECHO OFF
SETLOCAL
SET /P "colu=Enter column name:"
:Prompt
REM Clear any existing values.
SET "sn="
ECHO Enter a blank value to stop the operation.
SET /P "sn=Enter ID:"
REM Check for exist conditions.
IF "%colu%"=="" GOTO :EOF
IF "%sn%"=="" GOTO :EOF
REM If we get here, data was entered for both
sqlcmd -U USER -P PWORD -S SERVER -d DBNAME-i sqlSCRIPT.sql -o LOG.txt -v delete=%colu% d_id=%sn%
ECHO.
ECHO.
REM Ask again.
GOTO Prompt
:EOF
ENDLOCAL
This will keep prompting until you enter a blank value for either colu or sn. Also, I noticed you are using %%I in your SQL statement - I think you meant to use %sn% instead.

Related

How could I update values in one batch file through another batch file

In BCP approach I need to get three values(Machine Name, UserName, Password) dynamically from another batch file.
First File is look like:
MACHINE_NAME=IN-L20054
DB_UserName=sa
DB_Password=sa
pause
Second file is look like:
bcp.exe ExportDB.dbo.AddressCountry OUT "C:\Temp\AddressCountry.bcp" -S "MACHINE_NAME" -U "DB_UserName" -P "DB_Password" -n -q
bcp.exe ExportDB.dbo.CI OUT "C:\Temp\CI.bcp" -S "MACHINE_NAME" -U "DB_UserName" -P "DB_Password" -n -q
pause
The need behind this is, if we run these file in another machine, the only thing respective person need to do is to update and run first file with there Machine Name, UserName and Password
I tried solution but did not get succeed.
Could someone help me out here. ?
Strings can be passed from one batch file to another one either via arguments or via environment variables or via a text file.
1. Pass strings via arguments
Main.bat:
call "%~dp0Export.bat" "IN-L20054" "User" "Password"
call "%~dp0Export.bat" "Other Machine" "Other User" "Other Password"
Export.bat:
bcp.exe ExportDB.dbo.AddressCountry OUT "C:\Temp\AddressCountry.bcp" -S "%~1" -U "%~2" -P "%~3" -n -q
bcp.exe ExportDB.dbo.CI OUT "C:\Temp\CI.bcp" -S "%~1" -U "%~2" -P "%~3" -n -q
2. Pass strings via environment variables
Main.bat:
set "MACHINE_NAME=IN-L20054"
set "DB_UserName=User"
set "DB_Password=Password"
call "%~dp0Export.bat"
set "MACHINE_NAME=Other Machine"
set "DB_UserName=Other User"
set "DB_Password=Other Password"
call "%~dp0Export.bat"
Export.bat:
bcp.exe ExportDB.dbo.AddressCountry OUT "C:\Temp\AddressCountry.bcp" -S "%MACHINE_NAME%" -U "%DB_UserName%" -P "%DB_Password%" -n -q
bcp.exe ExportDB.dbo.CI OUT "C:\Temp\CI.bcp" -S "%MACHINE_NAME%" -U "%DB_UserName%" -P "%DB_Password%" -n -q
3. Pass strings via text file
In this example vertical bar | is used as delimiter which would be interpreted as redirection operator on not being escaped with caret character ^. It is of course possible to use any other character as delimiter like ; or , or a tab character.
(
echo IN-L20054^|User^|Password
echo Other Machine^|Other User^|Other Password
) >"%TEMP%\Export.tmp"
call "%~dp0Export.bat"
del "%TEMP%\Export.tmp"
Export.bat:
for /F "usebackq tokens=1-3 delims=|" %%I in ("%TEMP%\Export.tmp") do (
bcp.exe ExportDB.dbo.AddressCountry OUT "C:\Temp\AddressCountry.bcp" -S "%%~I" -U "%%~J" -P "%%~K" -n -q
bcp.exe ExportDB.dbo.CI OUT "C:\Temp\CI.bcp" -S "%%~I" -U "%%~J" -P "%%~K" -n -q
)
4. Both batch files merged together
for %%# in ("IN-L20054|User|Password" "Other Machine|Other User|Other Password") do (
for /F "tokens=1-3 delims=|" %%I in (%%#) do (
bcp.exe ExportDB.dbo.AddressCountry OUT "C:\Temp\AddressCountry.bcp" -S "%%~I" -U "%%~J" -P "%%~K" -n -q
bcp.exe ExportDB.dbo.CI OUT "C:\Temp\CI.bcp" -S "%%~I" -U "%%~J" -P "%%~K" -n
)
)
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
del /?
echo /?
for /?
set /?
See also the Microsoft article about Using command redirection operators.

conditional print in a batch file

I have a very simple batch file that runs a SQL query file and copies the results to a printer. The problem is it prints even if the results of the query is 0 rows. How can I only print if there is data?
cd stock
sqlcmd -i testquery.sql -S localhost -U User -P password -o testresults.txt
copy testresults.txt \\printserver\share
sqlcmd -i ems_update.sql -S localhost -U User -P password
del c:\stock\testresults.txt
exit
Ok, this is what I have now:
cd c:\stock
sqlcmd -i testquery.sql -S localhost -U User -P password -o testresults.txt
#find /c /i "0 rows" "C:\stock\testresults.txt" > NUL
if %ERRORLEVEL% EQU 1 (
pause
) else (
copy c:\stock\testresults.txt \\printserver\share)
pause
sqlcmd -i ems_update.sql -S localhost -U User -P password
I cannot get the copy command to run now. What am I missing??
thanks
Take a file that you know has 0 data.for /f "delims=" %%A in ('type nodata.txt') do set nodata=%%AThenfor /f "delims=" %%A in ('type testresults.txt') do set test_result=%%AThenif not %nodata%==%test_result% copy testresults.txt \printserver\shareThis will only work if the same exact no data file is produced, like no timestamps.or
use find which returns %errorlevel%==1 if it does not find a phrase in file and 0 if it does.
Just an idea - you can check if size of the file is 0. In Bash it would be something like this:
if [ ! -s ./testresults.txt ] ; then
rm ./testresults.txt
# or do something else
else
copy testresults.txt \\printserver\share
fi

What am I doing wrong in this batch file?

When I run the below batch file code, it thinks that the server address is 'dbuser' and the Database is 'False'
What am I doing wrong?
Here is the code:
#echo off
set toolspath=C:\Program Files (x86)\Folder\Application
Set ApplicationServer=00.0.00.000
Set ApplicationDatabase=dbApplication
Set ApplicationUser=dbuser
Set ApplicationPassword=abcdefg
Set ApplicationUpgradeFromPre12_5=False
REM echo "Attaching dbApplication .. "
REM osql -S %ApplicationServer% -U %ApplicationUser% -P %ApplicationPassword% -i %ApplicationScriptsPath%\AttachApplicationDatabase.sql
REM osql -S %ApplicationServer% -U %ApplicationUser% -P %ApplicationPassword% -i %ApplicationScriptsPath%\SetDBVersion.sql
REM echo "Done."
call ApplicationUpgradeScripts.bat %%2 %ApplicationUser% %ApplicationPassword% %ApplicationDatabase% %ApplicationUpgradeFromPre12_5%
#if ERRORLEVEL 1 goto ERRORSEXIT
#Echo %ApplicationDatabase% Database Updated Successfully.
goto FINISH
:ERRORSEXIT
#Echo Error: Database Excecuted With Error. To Find out Exact Error see file ErrorLog.log
exit /B 1
goto ENDBUILD
:FINISH
#Echo All Databases Excecuted Successfully.
exit 0
:ENDBUILD
pause

Batch script check array variable always goes to ELSE statement

I have a batch script which asks the user to input a server. Then it checks if it is from an array, where the servers require 3 password to login. Otherwise 2 passwords are needed. I check this in a for loop but always end up going to the else statement. Why? Here is the code:
#echo off
set arrayserver[0]=server1
set arrayserver[1]=server2
set arrayserver[2]=server3
set arrayserver[3]=server4
set arrayserver[4]=server5
set arrayserver[5]=server6
set arrayserver[6]=server7
set arrayserver[7]=server8
set arrayserver[8]=server9
set arrayserver[9]=server10
set arrayserver[10]=server11
set arrayserver[11]=server12
set arrayserver[12]=server13
set arrayserver[13]=server14
set arrayserver[14]=server15
set arrayserver[15]=server16
set arrayserver[16]=server17
set arrayserver[17]=server18
set arrayserver[18]=server19
set arrayserver[19]=server20
set arrayserver[20]=server21
set arrayserver[21]=server22
set arrayserver[22]=server23
set arrayserver[23]=server24
set arrayserver[24]=server25
set arrayserver[25]=server26
set arrayserver[26]=server27
set user2=user2
set user3=user3
set i=0
set /p server=Enter server:
for /F "tokens=2 delims==" %%s in ('set arrayserver[') do (
if "%server%" == "%%s" (
goto breakit
) else (
goto breakit2
))
:breakit
echo You will be prompted for 3 passwords:
echo -pass1
echo -pass2
echo -Oracle user
echo ssh -t -A %user2%#hop2 ssh -t -A %EDSUSER%#%server% su - oracle > C:\Temp\linkche.txt
"C:\Program Files (x86)\Putty\putty.exe" -ssh -A -t %USER%#hop1 -m C:\Temp\linkche.txt
del C:\Temp\linkche.txt
goto :oef
:breakit2
echo You will be prompted for 2 passwords:
echo -pass1
echo -Oracle user
echo ssh -t -A %user2%#hop2 ssh -A oracle#%server% > C:\Temp\linkche.txt
"C:\Program Files (x86)\Putty\putty.exe" -ssh -A -t %USER%#hop1 -m C:\Temp\linkche.txt
del C:\Temp\linkche.txt
goto :oef
Well, that's simple. You are in a loop but after checking the first server you are entering the ELSE case. So you are jumping out of the loop after the first iteration. You can verify this by entering server1. In this case the IF case is executed. Further, GOTO :oef makes no sense. I suppose you want to do GOTO :EOF. While EOF means EndOfFile, OEF means nothing (or possibly OfEndFile? :D).
To fix your problem you should modify your loop like this:
...
for /F "tokens=2 delims==" %%s in ('set arrayserver[') do (
if "%server%" == "%%s" (
goto breakit
)
)
goto breakit2
...
Now you will jump to breakit if the input is between server1 and server27 or to breakit2 otherwise. And don't forget to replace oef with eof.
You do not need to iterate over the array elements. If you define the array with the server values as subscripts with any value in the element (instead of numeric subscripts with the server in the value), then you may directly test if such server exist via a if defined arrayserver[%server%] ... command. I also use a simpler way to define the array.
#echo off
rem Define the server array with the server *in the subscript*; the assigned value does NOT matter
for %%a in (server1 server2 server3 server4 server5 server6 server7 server8 server9 server10
server11 server12 server13 server14 server15 server16 server17 server18 server19 server20
server21 server22 server23 server24 server25 server26 server27) do (
set arrayserver[%%a]=3
)
set user2=user2
set user3=user3
set /p server=Enter server:
if not defined arrayserver[%server%] goto passwords-2
:passwords-3
echo You will be prompted for 3 passwords:
echo -pass1
echo -pass2
echo -Oracle user
echo ssh -t -A %user2%#hop2 ssh -t -A %EDSUSER%#%server% su - oracle > C:\Temp\linkche.txt
"C:\Program Files (x86)\Putty\putty.exe" -ssh -A -t %USER%#hop1 -m C:\Temp\linkche.txt
del C:\Temp\linkche.txt
goto :eof
:passwords-2
echo You will be prompted for 2 passwords:
echo -pass1
echo -Oracle user
echo ssh -t -A %user2%#hop2 ssh -A oracle#%server% > C:\Temp\linkche.txt
"C:\Program Files (x86)\Putty\putty.exe" -ssh -A -t %USER%#hop1 -m C:\Temp\linkche.txt
del C:\Temp\linkche.txt
goto :eof
You may even define array elements with different values for 2 and 3 passwords, and then directly use their values to go to the appropriate section with no if command!
setlocal EnableDelayedExpansion
rem Servers with 3 passwords:
for %%a in (server1 server2 server27) do set arrayserver[%%a]=3
rem Servers with 2 passwords:
for %%a in (serverA serverB serverZ) do set arrayserver[%%a]=2
set /p server=Enter server:
goto passwords-!arrayserver[%server%]!
For further info about array management in Batch files, see this post.

Using SQLCMD in a batch file, how can I parse the response and check for an error?

I'm using SQLCMD to get the count of rows in a table, but I also want to be aware if the query hits an error.
The sqlcmd I'm using looks like this:
sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%"
If it works, it will return:
-----------
10205
(1 rows affected)
(Note, there is a blank line above the ------- for the column name I'm not specifying.)
If I pass in a table that doesn't exist, I get the following response:
Msg 208, Level 16, State 1, Server devServer, Line 1
Invalid object name 'dbo.no_table'.
Since I have the -b flag, I can check ERRORLEVEL for a value (in this case, 1).
To store the count variable, I've been using the following line:
for /F %%i in ('sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%" ^| findstr /r "[^(][0-9]"') do SET /a rec_count=%%i
After the for, %errorlevel% returns 0. Even inside the do, errorlevel is 0.
Is there any simple way to run sqlcmd, store the count if there is not an error, and print both lines if there is an error?
Commands that are executed by FOR /F are implicitly executed via a new CMD session. For example, with for /f %a in ('echo hello') do ..., the command that is executed becomes C:\Windows\system32\cmd.exe /c echo hello.
Your command is properly setting the ERRORLEVEL, but then the value is lost as soon as the child CMD session terminates and control is returned to your batch script.
So the /b option is not really doing any good for you, and can be dropped.
You can suppress the header info by adding the -h -1 option.
You can suppress the (1 rows affected) message by prefixing your command with set nocount on;
You can add the -r 1 option to cause error messages to appear on stderr instead of stdout. This will prevent FOR /F from processing any error, and the error message will appear on the screen instead.
You can clear the rec_count variable before you execute the command. Then it will remain undefined if there was an error, else it will contain the count if there was no error.
set "rec_count="
for /f %%A in (
'sqlcmd -S %server% -U %user% -P %pass% -h -1 -r 1 -Q "set nocount on;select count(*) from %table%"'
) do set "rec_count=%%A"
if not defined rec_count echo There was an error!
One other thing you might consider is using environment variables recognized by SQLCMD for your server, username, and password. Then you won't have to use the -S, -U, or -P options. This is especially handy if your batch script runs many SQLCMD commands.
set "sqlcmdServer=YourServer"
set "sqlcmdUser=YourUserName"
set "sqlcmdPassword=YourPassword"
set "rec_count="
for /f %%A in (
'sqlcmd -h -1 -r 1 -Q "set nocount on;select count(*) from %table%"'
) do set "rec_count=%%A"
if not defined rec_count echo There was an error!
The reason errorlevel does not seem to be getting set is because the for command is executing successfully, regardless of how the code that it loops through executes. So you can only interact with the errorlevel that is set by the sqlcmd command on the same line (inside the for loop brackets).
You should be able to use || (double pipe) after the sqlcmd command. Any code after || will only run if the previous command fails. Example:
notACommand || echo test
Will return "test". While the following will output only "a command":
echo a command || echo test
I can't test it, but something like the following should work for you:
for /F "EOL=(" %%i in ('sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%" ^|^| echo fail') do (
SET rec_count=%%i
)
if "%rec_count%"=="fail" echo SQL command failed
If the output is exactly as you say, then you should not need the findstr command - just set ( open bracket as an EOL character in the for loop, so you effectively drop the "(1 rows affected)" line. You will probably want to use the variables differently, but this is just one way you can tell if the sqlcmd command has failed or not.
As for outputting the error - a bad solution is to run the same sqlcmd command again. Something like the following:
set command=sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%"
for /F "EOL=(" %%i in ('%command% ^|^| echo fail') do SET rec_count=%%i
if "%rec_count%"=="fail" (%command%) else echo rec_count is %rec_count%
Note that I removed the /a switch when setting the rec_count variable, because it can now be set as a word.

Resources