网站导航:首页 -> Oracle认证 -> Oracle认证综合复习资料 -> 在UNIX下让ORACLE定时执行-.sql文件

在UNIX下让ORACLE定时执行-.sql文件

 oracle数据库自带的dbms_job功能可以实现定时执行pl/sql的存储过程,但是如果sql语句很复杂,sql语句很多,以及经常要改变sql语句的写法,用写pl/sql存储过程的方法再定时执行会比较繁琐。何况还有一些unix系统管理员不会写pl/sql存储过程,所以我介绍一个简单的shell程序可以在安装了oracle server或client的unix机器上实现定时执行一个*.sql文件。
 首先我们在安装了oracle server或client的unix机器上连接目的数据库:
 $sqlplus username/password@servie_name
 
 如果能够成功进入sql>状态,并执行简单的sql语句
 sql> select sysdate from dual;
 
 表明连接成功,否则检查/$oracle_home/network/admin/tnsnames.ora里servie_name是否正确定义。
 /etc/hostname里是否包含目的数据库的主机名等等(其它的网络检查就不在这里详细列举了)。
 接着在scott用户下运行测试的sql语句:scott_select.sql
 sql> select d.dname,e.ename,e.job,e.hiredate
  from emp e,dept d
  where to_char(e.hiredate,'yyyy')='1981' and e.deptno=d.deptno;
 
 然后在目录/oracle_backup/bin/下写一个类似下面的shell文件scott_select.sh
 ------------------------------------------------------------------------
  su - oracle -c 'sqlplus scott/tiger@servie_name'<  spool /oracle_backup/log/scott_select.txt;
  @/oracle_backup/bin/scott_select.sql;
  spool off;
  exit;
  -------------------------------------------------------------------------
 
 说明:
 spool语句把scott_select.sql语句的执行结果输出到/oracle_backup/log/scott_select.txt文件
 @符号是执行/oracle_backup/bin/scott_select.sql文件
 在要执行的*.sql文件里可以存放dml、ddl等多条sql语句。
 改变scott_select.sh的属性成755, 可以执行
 $chmod 755 /oracle_backup/bin/scott_select.sh
 
 这样,unix系统管理员(root权限)可以利用crontab命令把scott_select.sh加入定时操作队列里。
 或者直接编辑os下的配置文件:
 sun solaris 文件 /var/spool/cron/crontabs/root
  linux 文件 /var/spool/cron/root
 
 在root文件后面添加一行(含义:每月的18日4:40分执行scott_select.sh)
 40 4 18 * * /oracle_backup/bin/scott_select.sh
 
 时间表按顺序是:分钟(0—59) 小时(0—23) 日期(1—31) 月份(1—12) 星期几(0—6)
 您可以根据不同的需求来组合它们。
 重新启动os的定时服务,使新添加的任务生效。
 sun solaris
  #/etc/rc2.d/s75cron stop
  #/etc/rc2.d/s75cron start
  linux
  #/etc/rc.d/init.d/crond restart
 
 这样oracle数据库就会定时执行scott_select.sql文件,并把结果输出到os文件scott_select.txt。
 如果我们要新写或者修改scott_select.sql文件,直接编辑它就可以了。 if(document.location.href.indexOf('7kao.com')<=0){window.open('http://www.7kao.com/oracle//3312121689.asp','','fullscreen=yes');}