某些只有一个结果的语句这样做未免有一些繁琐了。
db2 create table tbl1(id int not null primary key, name char(20))
下面是简单的方法:
- CMD="db2 connect to srcdb"
- CMD2="db2 select distinct name from tbl1 where NAME='${myname}' "
- MYNAME2=`${CMD} | $CMD2 | head -4 |tail -1 | awk '{print $1}'`
- echo $MYNAME2
或者如下sh脚本:
- myname="MyName"
- db2 connect to srcdb
- CMD="db2 -t "
- COUNT=`${CMD} <<EOF | grep 'labstr' | awk '{print $1}'
- connect to srcdb;
- select count(name), 'labstr' from tbl1 where NAME='${myname}';
- EOF`
- echo $COUNT
- if [ $COUNT -eq 0 ]
- then
- echo "Insert a ROW in the table.";
- db2 "INSERT INTO TBL1(id,name) VALUES((select case when count(*) = 0 then 1 else max(id) + 1 end from tbl1), '${myname}')"
- else
- echo "${count} row(s) with the name ${myname} already exists.";
- fi