将shell变量传递给SQL语句

时间:2015-08-30 09:22:06

标签: sql shell sqlplus

我想将shell变量传递给sql语句。 shell脚本和SQL语句都存在于同一个脚本文件中。 我想在SQL语句中使用变量retMonthretLastDayretPrvYear的值。 以下是代码。

如果我执行此操作,则会打印- " partition_date between '01--' and '--' \ 0 0] 1 1] 12-DEC-14 1"

如何在SQL语句中包含retMonthretLastDayretPrvYear的值?

echo $retMonth  //This prints 07
echo $retLastDay //This prints 31
echo $retPrvYear  //This prints 2015

count=$(sqlplus -s  ${DBA_ORACLE_USER}/${DBA_ORACLE_PWORD}@${ORACLE_SID} <<END
#connect ${DBA_ORACLE_USER}/${DBA_ORACLE_PWORD}@${ORACLE_SID}
set serveroutput on
set linesize 1000
set heading off
set feedback off
define lastMonth=$retMonth
define lastYear=$retPrvYear
define lastDay=$retLastDay
SELECT count(1)
FROM MYTABLE
WHERE partition_date between '01-$lastMonth-$lastYear' and '$lastDay-$lastMonth-$lastYear'
  );
END
)

1 个答案:

答案 0 :(得分:0)

尝试直接使用引用的shell变量,而不使用define指令:

count=$(sqlplus -s "${DBA_ORACLE_USER}/${DBA_ORACLE_PWORD}@${ORACLE_SID}" <<END
set serveroutput on
set linesize 1000
set heading off
set feedback off

SELECT count(1)
  FROM MYTABLE
  WHERE partition_date between 
   "01-$retMonth-$retPrvYear" and "$retLastDay-$retMonth-$retPrvYear";
END
)