在工作日截断表的功能

时间:2014-02-24 12:13:31

标签: oracle plsql oracle11g

如果星期几是星期二到星期六,我想编写一个截断特定表的函数。我尝试了以下代码,但if条件不起作用。有人可以帮帮我。

create or replace FUNCTION   TRUNCATE_TABLE    RETURN NUMBER
IS
  --DECLARE VARIABLES
  l_day_of_week    VARCHAR2(15);
  l_table_name CONSTANT VARCHAR2(40) := 'ABC';

BEGIN

  EXECUTE IMMEDIATE 'select (to_char(sysdate,''DaY'')) from dual ' 
     INTO l_day_of_week ;

  IF l_day_of_week in ('Monday','Tuesday','Wednesday',
                       'Thursday','Friday','Saturday') 
  THEN  
    EXECUTE IMMEDIATE 'TRUNCATE TABLE ABC' ;
    dbms_output.put_line(l_day_of_week);
  END IF;

  RETURN 0;

END;

2 个答案:

答案 0 :(得分:4)

IF TRIM(l_day_of_week) in ('Monday','Tuesday','Wednesday',
                       'Thursday','Friday','Saturday') 

默认返回类型类似于CHAR(9) .. <9> 最大一周中某一天的长度(星期四)

所以Monday会附加空格!!除非您使用FMDAY

因此,TRIM()将删除所有填充的尾随空格!

您可以使用&#39; FM&#39;来试用下面的演示。 (Format Mask

退出FM

SQL> select to_char(sysdate+level,'Day'),length(to_char(sysdate+level,'Day')) as length from dual
  2  connect by level <= 7;

TO_CHAR(SYSDATE+LEVEL,'DAY')             LENGTH
------------------------------------ ----------
Tuesday                                       9
Wednesday                                     9
Thursday                                      9
Friday                                        9
Saturday                                      9
Sunday                                        9
Monday                                        9

7 rows selected.

使用FM

SQL> select to_char(sysdate+level,'FMDAY'),length(to_char(sysdate+level,'FMDaY')) as length from dual
  2  connect by level <= 7;

TO_CHAR(SYSDATE+LEVEL,'FMDAY')           LENGTH
------------------------------------ ----------
TUESDAY                                       7
WEDNESDAY                                     9
THURSDAY                                      8
FRIDAY                                        6
SATURDAY                                      8
SUNDAY                                        6
MONDAY                                        6

7 rows selected.

最后,

l_day_of_week = to_char(sysdate,'DaY')

会不会,您保存动态SQL调用!

答案 1 :(得分:3)

假设您希望每天截断一次此表,我将使用DBMS_SCHEDULER作业并将日期逻辑放在作业中:

create or replace PROCEDURE TRUNCATE_TABLE    
IS
BEGIN
  EXECUTE IMMEDIATE 'TRUNCATE TABLE ABC' ;
END;

begin
  dbms_scheduler.create_job(
      job_name => 'JOB_TRUNCATE_TABLE'
     ,job_type => 'PLSQL_BLOCK'
     ,job_action => 'begin truncate_table; end; '

     ,start_date      => to_timestamp_tz('2014-02-24 05:00:00 Europe/Berlin',
                                         'yyyy-mm-dd hh24:mi:ss tzr')
     ,repeat_interval => 'FREQ=DAILY;BYHOUR=22;BYDAY=Mon,Tue,Wed,Thu,Fri'
     ,enabled => TRUE
     ,comments => 'Truncate table job, runs Monday to Friday at 22:00');
end;