一种直观的方法,是将DB2命令的结果保存到一个文件之中,然后再从文件之中解析所需要的结果。但是对于


某些只有一个结果的语句这样做未免有一些繁琐了。

db2 create table tbl1(id int not null primary key, name char(20))

下面是简单的方法:
  1. CMD="db2 connect to srcdb"
  2. CMD2="db2 select distinct name from tbl1 where NAME='${myname}' "
  3. MYNAME2=`${CMD} | $CMD2 | head -4 |tail -1 | awk '{print $1}'`
  4. echo $MYNAME2

或者如下sh脚本:
  1. myname="MyName"
  2. db2 connect to srcdb
  3. CMD="db2 -t "
  4. COUNT=`${CMD} <<EOF | grep 'labstr' | awk '{print $1}'
  5. connect to srcdb;
  6. select count(name), 'labstr' from tbl1 where NAME='${myname}';
  7. EOF`
  8. echo $COUNT

  9. if [ $COUNT -eq 0 ]
  10. then
  11.     echo "Insert a ROW in the table.";
  12.     db2 "INSERT INTO TBL1(id,name) VALUES((select case when count(*) = 0 then 1 else max(id) + 1 end from tbl1), '${myname}')"
  13. else
  14.     echo "${count} row(s) with the name ${myname} already exists.";
  15. fi

09-06 15:41