ITPub博客

首页 > 数据库 > 数据库开发技术 > 使用批处理脚本或SHELL配合SQL脚本

使用批处理脚本或SHELL配合SQL脚本

原创 数据库开发技术 作者:charsi 时间:2010-11-19 18:46:50 0 删除 编辑

有时候我们在写一些数据库脚本的时候,通过SQLPLUS设置变量可能很麻烦.此时可以利用操作系统的脚本.
比如当系统为*NIX时可以使用SHELL脚本,当系统为Windows时可以通过批处理脚本配合使用.

下面是两种平台的两个示例:
(1)UNIX或Linux平台
下面这个脚本,是通过在系统中取得当前时间的年月,然后传递给SQLPLUS拼成表的分区,可以用来优化SQL

TESTDB /oravl01/oracle/charsi> cat xx_test.sh
CUR_MONTH=`date +%Y%m`

sqlplus charsi/charsi@testdb <set timing on
select count(1)
from test_parti_table partition (month_${CUR_MONTH}) t
where t.object_id in (10, 20, 30)
and t.create_time > (sysdate - 1 / 96);
EOF

TESTDB /oravl01/oracle/charsi>
TESTDB /oravl01/oracle/charsi>

上面这个是一个监控脚本,实时取15分钟之内的数据,本例仅仅是用来演示从系统向sqlplus中传递变量的.


(2)Windows平台
下面是一个windows批处理脚本示例,模拟的是通过系统向sqlplus中传递变量,然后执行sql
非常感谢itpub上xqmei的答复

文件xxxx.bat的内容为:

@echo off
@set aa=test_charsi
set ORACLE_SID=ORCLXX
if "%1"=="__get_sql" goto :get_sql

%0 __get_sql | sqlplus "/ as sysdba"
goto :end
:get_sql
echo set timing on
echo select * from dual;
echo select '%aa%' from dual;
echo exit;
:end

执行该脚本
C:9_TMP>xxxx.bat

SQL*Plus: Release 9.2.0.1.0 - Production on 星期六 11月 20 18:36:02 2010

Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.


连接到:
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production

SQL> SQL>
DU
--
X

已用时间: 00: 00: 00.00
SQL>
'TEST_CHARSI'
----------------------
test_charsi

已用时间: 00: 00: 00.00
SQL> 从Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production中断开

C:9_TMP>

该脚本含义一个简单介绍:
@echo off ----echo off前面加@,就是在界面上不显示"echo off"
@set aa=test_charsi ----设置aa变量
set ORACLE_SID=ORCLXX ---设置ORACLE_SID
if "%1"=="__get_sql" goto :get_sql -----如果该脚本的第一个参数为__get_sql,则跳转到:get_sql

%0 __get_sql | sqlplus "/ as sysdba" -----执行:脚本名 __get_sql |sqlplus "/ as sysdba"。%0的意思是当前执行的脚本,相当于在脚本中执行了该脚本

goto :end
:get_sql ----设置get_sql中的内容
echo set timing on
echo select * from dual;
echo select '%aa%' from dual;
echo exit;
:end


当然在Windows下完全可以先把文件生成出来再通过sqlplus "/ as sysdba" @sql_script.sql来执行,这样也比较简洁直观,本例仅仅是作为演示.

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/23850820/viewspace-1041798/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2010-05-04

  • 博文量
    96
  • 访问量
    406716