2011-12-06 39 views
1

我有一段時間(沒有日期組件),例如上午9點,假設它是當前時間。我想查詢所有從表中開始和結束時間存儲爲時間戳的表。查詢開始時間和結束時間之間的Current_Timestamp(無日期!)Oracle PL/SQL

我該怎麼做?我應該以不同的方式儲存嗎

我嘗試了類似SELECT * FROM tab1 WHERE (current_timestamp - current_date) BETWEEN starttime AND endtime;但不起作用,因爲計算的差異總是(幾乎)爲零。我可以用EXTRACT命令做一些事情,但這似乎有點複雜......難道沒有一種簡單的方法可以做到這一點嗎?

基本上,它們存儲約會。

在此先感謝。

回答

4

嘗試:

SELECT * FROM tab1 
WHERE (current_timestamp - TRUNC(current_date)) BETWEEN starttime AND endtime 
+0

十分感謝工程對它們進行測試。 – user1054247

0

TO_CHAR函數總是有益的,當涉及到比較日期。如果你只是想比較時間戳的時間部分使用

to_char(your_time, 'hh24mm') 
2

這兩種選擇,對我,提取似乎並不複雜

where 16 between extract(hour from start_ts) and extract(hour from end_ts) 
where '16' between to_char(start_ts, 'hh24') and to_char(end_ts, 'hh24') 

請注意,如果你把一個(start_ts,and_ts)上的普通索引,那麼這個查詢就不會使用它,而是會掃描整個表。你需要基於函數的索引來避免全表掃描http://www.dba-oracle.com/t_garmany_easysql_function_based_indexes_fbi.htm

還有第三個選項可以使用普通索引,但這不是你要求的,因爲在這裏你必須提供一天在這裏,不僅僅是小時

where to_timestamp('2011.12.06. 17', 'yyyy.mm.dd. hh24') between start_ts and end_ts 

場的第四個選項將直接存儲開始和結束時間,而不是時間戳值。

繼承人的代碼我

select * from 
(select 
1 as id, 
to_timestamp('2011.12.06. 16:10:32', 'yyyy.mm.dd. hh24:mi:ss') as start_ts, 
to_timestamp('2011.12.06. 16:18:32', 'yyyy.mm.dd. hh24:mi:ss') as end_ts 
from dual 
union 
select 
2 as id, 
to_timestamp('2011.12.06. 16:20:32', 'yyyy.mm.dd. hh24:mi:ss') as start_ts, 
to_timestamp('2011.12.06. 17:18:32', 'yyyy.mm.dd. hh24:mi:ss') as end_ts 
from dual 
union 
select 
3 as id, 
to_timestamp('2011.12.06. 17:30:32', 'yyyy.mm.dd. hh24:mi:ss') as start_ts, 
to_timestamp('2011.12.06. 18:18:32', 'yyyy.mm.dd. hh24:mi:ss') as end_ts 
from dual 
) 
where 16 between extract(hour from start_ts) and extract(hour from end_ts) 
--where '16' between to_char(start_ts, 'hh24') and to_char(end_ts, 'hh24') 
--where to_timestamp('2011.12.06. 17', 'yyyy.mm.dd. hh24') between start_ts and end_ts 
; 
+0

非常感謝您的幫助,稍後我會閱讀,現在我有一些演講... – user1054247

+0

好的。只是爲了澄清:馬克的答案對當前時間場景非常有用。在我的回答中,第三種選擇等同於馬克的答案。 – bpgergo

相關問題