can I run multiple db2 commands in one command?
i.e: from cmd:
db2cmd /c db2 /c connect to sample user sample_user using sample_pwd /c
"SELECT * FROM table;"
I also tried the following:
db2 connect to sample user db2admin using pwd; EXPORT TO result.csv OF DEL
MODIFIED BY NOCHARDEL SELECT * FROM alarms;
but didn't work with the following error:
SQL0104N An unexpected token "EXPORT" was found following
"". Expected tokens may include: "NEW". SQLSTATE=42601
as an example, for VERTICA, vsql tool, this can be done this way:
vsql -h localhost -U user -w pwd -c "SELECT * FROM alarms" -A -o
"alarms.csv" -F "|" -P footer=off -q
You appear to be using Microsoft Windows db2cmd.exe .
Your question has nothing to do with Db2 per se, but it is instead more about CMD (cmd.exe) scripting syntax, a legacy scripting language for batch files by Microsoft that still works on Windows-10, and which also works in db2cmd.exe.
In a db2cmd.exe shell you can use the "&&" sequence between distinct Db2 commands (and each such command must have the db2 prefix). Additionally each such command line has to escape any of the characters that are special characters to the shell itself. By default the escape character is a caret (^) symbol.
For example db2 connect to dbname && db2 ^"export to alarms.csv of del ... select ^* from alarms^" && db2 connect reset
( I show the ^ before any " that you might want to pass to Db2-CLP ).
But that && will require that each command returns a zero exit code, which might not be what you want, although it is usually the safest option. If a previous command fails then subsequent commands will not run.
If you want to tolerate some non-zero exit codes, use bracketing ( ... ) to group commands, and then use the && or & outside the brackets depending on your requirements. You can read about CMD scripting in any good book, plenty of examples online.
However, when scripting for Db2 on Windows , it can be much wiser to append all of the commands (without the Db2 prefix) into a plain text file, and then ask the Db2 clp to execute the text file via the syntax db2 -tvf texfile. Doing it this way lets you add conditional logic inside the textfile, handle exceptions , avoid shell escaping requirements, etc. If you encapsulate all your logic inside a script, it makes it easier to test, and also easier to run from a single db2cmd /c .... command-line.
If you want to make a batch file (*.bat or *.cmd) that does not need the db2cmd prefix to be invoked, you can alter your batch file to have a few lines at the start of the batch file to re-execute itself via db2cmd.exe. This works better if your db2cmd.exe is already on the PATH environment variable, but if that is not the case then you can fully-qualify the absolute pathname to your db2cmd.exe inside the batch file. The lines to add at the start of the batch file are:
#rem re-execute via db2cmd if running from cmd.exe
#echo off
if "%DB2CLP%"=="" db2cmd /c /i /w "%0" %* & goto :EOF
db2 connect to sample user db2admin using pwd
if errorlevel 1 #echo "Failed to connect to database " && #goto :EOF
db2 "EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL SELECT * FROM alarms"
if errorlevel 3 #echo "Export from Db2 failed" && #goto :EOF
Additionally on Windows, you can use Powershell scripting to maniuplate Db2 databases, and you can also use Windows subsystem for unix to run Unix-style shell scripts in some configuration.
Your example's most direct comparison in Db2-land would be clpplus which lets you specify the database but you also have to provide login information (including a password or you can be prompted for it).
Within the db2cmd and db2 framework you have a couple options but most likely will want to use a script file.
One option: Set the registry variable DB2DBDFT to your default database. Personally, I dislike this option because it causes an implicit connection to a database that you may not have intended.
One option: Put your series of commands into a file and run that file. This is the more traditional way of running multiple commands. Commands can be terminated with a semi-colon and newline (it understands DOS and Unix differences here). You can use a different terminator by using -td # (for example). You would then invoke db2 -tf file.sql.
One option: A batch file. It's similar to above but you'd use the db2cmd environment to execute a batch that has the db2 commands in it. db2cmd gets you an appropriate environment for working with Db2. If you connect to a database in this environment you stay connected until you issue a CONNECT RESET, a TERMINATE, are forcibly disconnected, or your environment exits. So your batch file would simply have:
db2 connect to sample user db2admin using pwd
db2 "EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL SELECT * FROM alarms"
(note the quotes to keep the command line from substituting all the filenames in the current working directory where the * is)
Two options.
1-st:
db2cmd /i /w /c "db2 ^"connect to sample^" & db2 ^"values 1^" & db2 connect reset"
2-nd:
You may set the following Windows system environment variable DB2CLP to the value **$$** and run db2 commands from windows cmd directly afterwards like this:
db2 "connect to sample" & db2 "values 1" & db2 connect reset
Related
Does the Postgres client psql have a functionality like the ## of Oracle SQLPlus?
For those who are wondering what ## does: it allows to call a relative sql script from another script.
Quote from the manual:
\ir or \include_relative filename
The \ir command is similar to \i, but resolves relative file names differently. When executing in interactive mode, the two commands behave identically. However, when invoked from a script, \ir interprets file names relative to the directory in which the script is located, rather than the current working directory.
I have a problem with DB2CLP environment variable, on Windows 7 64, IBM_client64_V97 (to be connected with DB2).
Every time when i try to DB2 in Windows command prompt window, I receive this error:
DB21061E Command line environment not initialized.
and per this document using just this step:
2. at the prompt enter these commands:
db2cmd -i -w db2clpsetcp
echo %DB2CLP%
I fix that error, and "db2" command opens Command Line Processor for DB2 Client.
But it lasts only until windows CMD is open. As soon as I close it and reopen, I have to repeat process.
My question (being absolute novice to DB2) is:
How should I make that change permanent and
How this happened at the first place as I installed and setup everything according to the manual (including adding local user to DB2USERS and DB2ADMINS) groups?
When DB2 client is installed, it should have installed a functional window to the command line processor. Check here:
Start / All Programs / IBM DB2 / DB2copy1/ Command Line Processor
Note that DB2copy1 is the default location for the first db2 instance. The name may be different if user select the non-default name.
Shortcut to the CLP can be copied on the desktop.
Regarding the typing "DB2 ..some command..." in windows command prompt which causes described error explanation is as follows:
That's because the normal DOS (or Windows) prompt doesn't
automatically run the setup script that enables the DB2 commands.
When the setup runs, it puts the DB2 items first in the PATH variable.
That could conflict with other tools that also want to be first on the
search list.
If you've got both the DOS (Windows) and DB2 command line prompts on
your desktop, right click them and select Properties. You'll notice
that the system (DOS) prompt runs cmd.exe.
The DB2 prompt runs DB2CMD.exe from the DB2 libraries. The DB2 script
then runs DB2SETCP.BAT and finally DB2.EXE. (All of the DB2
executables should be in C:\Program Files\IBM\SQLLIB\BIN.)
So there are differences in the two prompts. For you purposes, try
running DB2SETCP.BAT from the normal DOS prompt. That may be
sufficient for your needs.
For my purposes I always have the DOS and DB2 prompts on my desktop
and just select the one that I need.
I am facing a problem in DB2. In my Oracle environment it was very easy for me to include multiple scripts in one master script, which were executed sequentially. e.g.:
Master.sql:
connect ....
#script1.sql
#script2.sql
Now I have to build up same logic in DB2 LUW. Is there a simple way to include multiple scripts in one master script? I would like to have one single db2 call from shell, which executes the master script and within all subscripts.
Regards
Jan
There is notrhing to stop you from creating a single file with multiple sql batches. In the Windows world, it would look like this:
Note: First you initialize the db2 command prompt.
db2cmd -c -w -i %1.bat
With as many of these as you want in the .bat file:
db2 -txf c:\Example\db2html.sql
In Linux, the db2clp is included in the shell once you load the db2profile ('. /home/db2inst1/sqllib/db2profile). In windows, you need to call db2cmd in order to use db2clp.
With a interactive db2clp, you cannot call db2 scripts via #scriptX, however, you can call them from the shell like
db2 -tvf script
However, if you use the CLP*Plus you can do almost everything you do in SQL*Plus. For more information: https://www.ibm.com/developerworks/community/blogs/IMSupport/entry/tech_tip_db2_s_new_clp_plus_utility?lang=en
I am writing a KSH script to accept a .sql file parameter followed by each schema that file is to be compiled in. The script assumes the .sql file is a DB2 9.7 procedure.
I believe I am stuck on the syntax of the db2 command for the termination character. We always use the at symbol ('#'), however the following snippet fails with error "DB21001E The option "-#" specified after the 'db2' command or in the DB2OPTIONS variable is incorrect." Any assistance would be greatly appreciated.
#!/bin/ksh
. $IBM_DB_DIR/db2profile
db2 connect to dwdev3
const_compil_string_suffix="-vtd# -f ../../stored_procedures/"
script_name="ETL.THING.sql"
db2 "$const_compil_string_suffix$script_name"
db2 terminate
I have confirmed that the resulting string command above the 'terminate' does work at linux prompt compiling the procedure as expected:
db2 -vtd# -f ../../stored_procedures/ETL.THING.sql
Thank you in advance.
Try losing the quotation marks:
db2 ${const_compil_string_suffix}${script_name}
I suspect the option string -vtd# might be the culprit.
When using single character options most unix command accept two types of options, those with and those without arguments.
Apparently the # character is being processed as an option argument, however the error message indicates it is seen as an option on its own.
Try separating the options, as in: -v -t -d#, reorder them. or remove one of the -t or -v options.
Beware though. I have no knowledge about the db2 cli. Experiment at your own risk.
Was the -t option added later?
How can I customize the prompt in the PostgreSQL command line tool psql (ideally in a per-user start-up script)?
In particular, I'd like to be able to change it while still including the character that indicates whether the command is multi-line (eg. =, -, ', etc.).
I'm running Ubuntu 10.04 (Lucid), PostgreSQL 8.4.4.
You can certainly customize the prompt.
From the documentation:
The prompts psql issues can be
customized to your preference. The
three variables PROMPT1, PROMPT2, and
PROMPT3 contain strings and special
escape sequences that describe the
appearance of the prompt. Prompt 1 is
the normal prompt that is issued when
psql requests a new command. Prompt 2
is issued when more input is expected
during command input because the
command was not terminated with a
semicolon or a quote was not closed.
Prompt 3 is issued when you run an SQL COPY command and you are expected to
type in the row values on the
terminal.
If you want to set the prompt on a per user basis, you can add the \set commands to the user's .psqlrc file.
So, your $HOME/.psqlrc would be something like this:
\set PROMPT1 '(%n#%M:%>) %`date +%H:%M:%S` [%/] \n%x%# '