1. 程式人生 > >日期型別的資料在Oracle資料庫中的儲存和查詢

日期型別的資料在Oracle資料庫中的儲存和查詢

使用Oracle資料庫,mybatis的對映檔案中日期型別的資料,如果定義為<result column =“UPDATED_DATE" jdbcType =“DATE” property =“updatedDate”/>,即使在後臺你為日期賦予年月日時分秒,但儲存到資料庫中將只會有年月日,而無時分秒。如果要儲存為年月日時分秒,日期型別的需要定義為jdbcType為 “timdstamp”

另外在PL SQL中通過SQL語句往oracle資料庫新增日期型別的資料方法為:

insert into table(j) values(to_date(‘2017-11-26 00:04:47’,‘yyyy-mm-dd hh24:mi:ss’));

即不能直接為為欄位賦值,需要通過to_date函式,後面接日期格式,修改也是一樣的:

update table t set t.updated_date=to_date(‘2018-10-11 08:15:16’,‘yyyy-mm-dd hh24:mi:ss’) where t.id=‘2152928’;

查詢當天資料的sql,在mybatis中可以這樣使用:select * from table where to_char(UPDATED_DATE,‘yyyy-mm-dd’)=to_char(sysdate,‘yyyy-mm-dd’) 在PL SQL中可以這樣用:select * from table where trunc(UPDATED_DATE)=trunc(sysdate)

下面是常用日期作為條件的查詢SQL

1.日期欄位型別為date

今天
select * from table where to_char(UPDATED_DATE,'dd')=to_char(sysdate,'dd')
昨天
select * from  table where to_char(UPDATED_DATE,'dd')= to_char(sysdate-1,'dd')
本週 
select * from table where to_char(UPDATED_DATE,'iw')=to_char(sysdate,'iw') 
本月 
select * from table where to_char(UPDATED_DATE,'mm')=to_char(sysdate,'mm') 
本季度 
select * from table where to_char(UPDATED_DATE,'q')=to_char(sysdate,'q')
  1. 日期欄位型別為varchar2,格式要與格式化的樣式匹配

    今天
    select * from table where to_char(to_date(UPDATED_DATE,‘yyyy-mm-dd hh24:mi:ss’),‘dd’)=to_char(sysdate,‘dd’)
    昨天
    select * from table where to_char(to_date(UPDATED_DATE,‘yyyy-mm-dd hh24:mi:ss’),‘dd’)=to_char(sysdate-1,‘dd’)
    本週
    select * from table where to_char(to_date(UPDATED_DATE,‘yyyy-mm-dd hh24:mi:ss’),‘iw’)=to_char(sysdate,‘iw’)
    本月
    select * from table where to_char(to_date(UPDATED_DATE,‘yyyy-mm-dd hh24:mi:ss’),‘mm’)=to_char(sysdate,‘mm’)
    本季度
    select * from table where to_char(to_date(UPDATED_DATE,‘yyyy-mm-dd hh24:mi:ss’),‘q’)=to_char(sysdate,‘q’)