1. 程式人生 > >除錯經驗——使用Oracle BETWEEN函式限定查詢結果的時間範圍(Limit data range in Oracle)

除錯經驗——使用Oracle BETWEEN函式限定查詢結果的時間範圍(Limit data range in Oracle)

需求:

要建立一個半年生成一次的報表給領導看。現有的做法是在資料庫中提取出資料後在Excel中通過filter篩選出最近半年的資料,沒錯,純手動操作(弊端有二:容易出錯,效率低)。如何自動化呢?使用VBA有點小題大做,通過SQL指令碼實現即可。該BETWEEN條件語句出場了。

程式碼:

AND UTABLE.UDATEFIELD BETWEEN TO_DATE('2017-12-01','YYYY-MM-DD') BETWEEN TO_DATE('2018-05-31','YYYY-MM-DD')

一槍頭搞定,哈哈。

順便看看Oracle Database SQL Language Reference中對BETWEEN CONDITION的描述:

----------------------------------------------------------------------------------------------------------------

BETWEEN Condition

A BETWEEN condition determines whether the value of one expression is in an interval
defined by two other expressions.


All three expressions must be numeric, character, or datetime expressions. In SQL, it is
possible that expr1 will be evaluated more than once. If the BETWEEN expression
appears in PL/SQL, expr1 is guaranteed to be evaluated only once. If the expressions
are not all the same data type, then Oracle Database implicitly converts the
expressions to a common data type. If it cannot do so, then it returns an error.

The value of
expr1 NOT BETWEEN expr2 AND expr3
is the value of the expression
NOT (expr1 BETWEEN expr2 AND expr3)
And the value of
expr1 BETWEEN expr2 AND expr3
is the value of the boolean expression:
expr2 <= expr1 AND expr1 <= expr3
If expr3 < expr2, then the interval is empty. If expr1 is NULL, then the result is NULL. If
expr1 is not NULL, then the value is FALSE in the ordinary case and TRUE when the
keyword NOT is used.
The boolean operator AND may produce unexpected results. Specifically, in the
expression x AND y, the condition x IS NULL is not sufficient to determine the value of
the expression. The second operand still must be evaluated. The result is FALSE if the
second operand has the value FALSE and NULL otherwise. See "Logical Conditions" on
page 7-8 for more information on AND.