Shell脚本调用SQL文格式
1. 定义需要执行的SQL文,以及需要输出文件
OUTFILE=${DATADIR}/${FILENAME}
SQLFILE=${DATADIR}/check_tradedetail.sql
2. 设置需要执行的SQL文
echo -n "
select tr.id || ',' || m.merchant_code || ',' || m.merchant_name || ',' || to_char(tr.trade_start_time, 'yyyy-mm-dd hh24:mi:ss')
|| ',' || tt.name || ',' || tr.bank_code || ',' || tr.fld3 || ',' ||
tr.trade_sum || ',' ||
case when tr.status = 0 then '待处理'
when tr.status = 1 then '处理中'
when tr.status = 2 then '成功'
when tr.status = 3 then '失败'
when tr.status = 4 then '待确认' end
from tvpay2.trade_record tr join tvpay2.merchant m on tr.provider_id = m.id
join tvpay2.trade_type tt on tr.trade_code = tt.code
where to_char(tr.fiscal_date, 'yyyyMMdd') = ${date} order by tr.trade_start_time;
" > $SQLFILE
echo -n "
select ''''||a.merchant_code || ',' || a.merchant_name || ',''' || a.id
|| ',' || (a.balance + nvl(b.acc, 0)) || ',' || (a.withdrawable_balance + nvl(b.acc, 0)) || ',' || a.frozen_balance from
(select tu.merchant_code, tu.merchant_name, a.* from tvpay2.account a join tvpay2.merchant_account_association ua
on a.id = ua.account_id join tvpay2.merchant tu on ua.merchant_id = tu.id ) a
left join
(select v.account_id, sum(v.credited - v.debited) as acc from tvpay2.voucher v
where v.create_time <= to_date('$input_datetime', 'yyyymmdd hh24:mi:ss') group by v.account_id) b
on a.id = b.account_id where a.balance + nvl(b.acc, 0) > 0;
" > $SQLFILE1
#备注 ||表示分隔符 ‘,’用于分隔字段使用 其中‘’‘’为了在第一个字段中添加'号,另外‘、'"’可以添加“号,这个可以用来解决文本文件,转换成csv格式时,数字错乱问题。
3. 输出文件格式设置及其执行SQL文
##set colsep' '; //域输出分隔符
##set numwidth 25 ; //输出number类型域长度,缺省为10
##set linesize 300; //输出一行字符个数,缺省为80
##set pagesize 0; //输出每页行数,缺省为24,为了避免分页,可设定为0,设为0后无域标题。
##set echo off; //显示start启动的脚本中的每个sql命令,缺省为on
##set newpage none; //页与页之间的分隔符
##set termout off; //显示脚本中的命令的执行结果,缺省为on
##set trimout on; //去除标准输出每行的拖尾空格,缺省为off
##set trimspool on; //去除重定向(spool)输出每行的拖尾空格,缺省为off
##set serveroutput on; //设置允许显示输出类似dbms_output
##set timing on; //设置显示“已用时间:XXXX”
##set verify off; //可以关闭和打开提示确认信息old 1和new 1的显示.
##set heading off; //输出域标题,缺省为on
##set feedback off; //回显本次sql命令处理的记录条数,缺省为on
##alter session set nls_date_format='YYYY-MM-DD_HH24:MI:SS';
sqlplus /nolog <<!
conn user/password@ORCL
set numwidth 25
set linesize 300
set pagesize 0
set echo off
set heading off
set newpage none
set termout off
set trimout on
set trimspool on
set serveroutput off
set timing off
set verify off
set feedback off
spool ${OUTFILE};
@${SQLFILE};
spool off;
!
4.格式化输出文件
sed -i '/SQL/d' $OUTFILE1
sed -i '/---/d' $OUTFILE1
sed -i 's/ //g' $OUTFILE1
sed -i '/^$/d' $OUTFILE1
5.将文本格式转换为csv格式
iconv -f "utf-8" -t "gbk" ${OUTFILE1} > OUTFILE1.csv