As my shell script is calling Db2 many times with an ultra long SQL statement, I would like to abstract the SQL statements from the script and put them into a .sql file, then run it from the Db2 command line processor db2 -f xxx.sql.
I want some of the SQL statements to use variables that are passed in from the shell script.
Is there any method like Oracle's sqlplus that can pass variables inside the .sql file by '&1'?
xxx.sql
SELECT * FROM TABLE_A WHERE FIELD_B > &1
CLP
db2 -f xxx.sql 999
This returns a DB21004E error:
DB21004E You cannot specify both an input file and a command when invoking
the Command Line Processor.
The
db2CLP on Linux/Unix/Windows does not support substitutable parameters, something that IBM omitted long ago.You can consider one the these options:
Use the java based
clpplustool instead of thedb2CLP to run scripts. It emulates some of the Oracle SQL*plus functionality, including the ability to pass positional parameters on the command line ,and reference them like&1and&2etc in your scripts. However, the scripts then need to use Oracle style syntax , although your Db2-server does not need Oracle compatibility. You also get more formatting control over the query output.Move the query logic into routines in the database(s), and invoke them with parameters in your scripts. For example call the queries as stored-procedures with input parameters.
dynamically generate your SQL scripts with the relevant parameters and continue to run them with the
db2CLP. In effect you are doing your own variable substitution, possible via tools likeawkandsedor similar.