Oracle
 SQL >> Datenbank >  >> RDS >> Oracle

Sekunden zwischen zwei Oracle-Timestamps berechnen

„Best Practice“

Welchen Ansatz Sie auch wählen, verpacken Sie ihn in eine Funktion, etwa seconds_between (from_date, to_date). Wie sie intern implementiert ist, spielt keine Rolle – wählen Sie die effizienteste Methode, denn dann weiß jeder, der Ihren Code liest, sofort, was vor sich geht.

Performance

Ich habe die beiden Methoden auf 11gR1 auf meinem Laptop (WinXP) mit dem untenstehenden Testfall gemessen. Die CAST-Variante war am schnellsten. (t1 ist die Basislinie, t2 nutzt die extract-Methode und t3 die cast-Methode.)

t1 (nothing) 3 t2 (extract) 338 t3 (cast) 101 t1 (nothing) 3 t2 (extract) 336 t3 (cast) 100 

Testskript

declare x TIMESTAMP := SYSTIMESTAMP; y TIMESTAMP := TRUNC(SYSDATE); n PLS_INTEGER; lc CONSTANT PLS_INTEGER := 1000000; t1 PLS_INTEGER; t2 PLS_INTEGER; t3 PLS_INTEGER; begin t1 := DBMS_UTILITY.get_time; for i in 1..lc loop n := i; end loop; t1 := DBMS_UTILITY.get_time - t1; t2 := DBMS_UTILITY.get_time; for i in 1..lc loop n := extract(day from (x-y))*24*60*60 + extract(hour from (x-y))*60*60 + extract(minute from (x-y))*60 + extract(second from (x-y)); end loop; t2 := DBMS_UTILITY.get_time - t2; t3 := DBMS_UTILITY.get_time; for i in 1..lc loop n := ( CAST( x AS DATE ) - CAST( y AS DATE ) ) * 86400; end loop; t3 := DBMS_UTILITY.get_time - t3; dbms_output.put_line('t1 (nothing) ' || t1); dbms_output.put_line('t2 (extract) ' || t2); dbms_output.put_line('t3 (cast) ' || t3); end;