oracle中sql语句 日期加减,SQL语句里对日期进行相加减

在sql server里可以使用:

where start_date <=

DateAdd(d,1,to_date('2005-12-09','yyyy-mm-dd'))

and completion_date >=

to_date('2005-12-09', 'yyyy-mm-dd') ;oracle中没有定义和sql server中一样的DateAdd函数,

oracle可以通过interval 'n' year/month/day/hour/minute/second/second(p,s)

的方式来增减时间

下面是在oracle中写的DateAdd函数

函数调用基本同sql server一样, 不过datepart部分需要以字符串的方式输入, 即

DateAdd(d,1,to_date('2005-12-09','yyyy-mm-dd'))

要改为

DateAdd('d',1,to_date('2005-12-09','yyyy-mm-dd'))

函数定义如下函数中的注释是datepart的新说明, 与sql server中的略有不同)

create or replace function DATEADD( datepart varchar2, num number, indate date ) return date is

Result date;

v_sql varchar2(1000);

v_datepart varchar2(30);

v_ms varchar2(13);

begin

v_datepart := lower(datepart);

/*

Datepart Abbreviations

year yy, y

quarter qq, q

month mm, m

day dd, d

week wk, w

hour hh, h

minute mi, n

second ss, s

millisecond ms

*/

case

when v_datepart in ('year','yy','y') then

v_sql := 'select :1 + interval '''||num||''' year from dual';

when v_datepart in ('quarter','qq','q') then

v_sql := 'select :1 + (interval ''3'' month) * '||num||' from dual';

when v_datepart in ('month','mm','m') then

v_sql := 'select :1 + interval '''||num||''' month from dual';

when v_datepart in ('week','wk','w') then

v_sql := 'select :1 + (interval ''7'' day) * '||num||' from dual';

when v_datepart in ('day','dd','d') then

v_sql := 'select :1 + interval '''||num||''' day from dual';

when v_datepart in ('hour','hh') then

v_sql := 'select :1 + interval '''||num||''' hour from dual';

when v_datepart in ('minute','mi','n') then

v_sql := 'select :1 + interval '''||num||''' minute from dual';

when v_datepart in ('second','ss','s') then

v_sql := 'select :1 + interval '''||num||''' second from dual';

when v_datepart in ('millisecond','ms') then

v_ms := to_char(num/1000,'fm999999990.000');

v_sql := 'select :1 + interval '''||v_ms||''' second(9,3) from dual';

else

RAISE_APPLICATION_ERROR(-20001, ''''||datepart||''' is not a recognized dateadd option.' );

end case;

execute immediate v_sql into Result using indate;

return(Result);

EXCEPTION

WHEN OTHERS THEN

RAISE ;

end DATEADD;

分享到:更多

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值