位置:首頁 > 數據庫 > PL/SQL教學 > PL/SQL關係運算符

PL/SQL關係運算符

關係運算符

關係運算符比較兩個表達式或值,並返回一個布爾結果。下表列出了所有PL/SQL支持的關係運算符。假設變量A=10,變量B=20,則:

運算符 描述 示例
= 檢查兩個操作數的值是否相等,如果是的話那麼條件為真。 (A = B) 結果為 false.
!=
<>
~=
檢查兩個操作數的值是否相等,如果值不相等,則條件變為真。 (A != B) 結果為 true.
> 檢查左邊的操作數的值是否大於右操作數的值,如果是的話那麼條件為真。 (A > B) 結果為 false.
< 檢查左邊的操作數的值是否小於右操作數的值,如果是的話那麼條件為真。 (A < B) 結果為 true.
>= 檢查左邊的操作數的值是否大於或等於右操作數的值,如果是的話那麼條件為真。 (A >= B)  結果為 false.
<= 檢查左邊的操作數的值是否小於或等於右操作數的值,如果是的話那麼條件為真。 (A <= B) 結果為 true.

示例:

DECLARE
   a number (2) := 21;
   b number (2) := 10;
BEGIN
   IF (a = b) then
      dbms_output.put_line('Line 1 - a is equal to b');
   ELSE
      dbms_output.put_line('Line 1 - a is not equal to b');
   END IF;

   IF (a < b) then
      dbms_output.put_line('Line 2 - a is less than b');
   ELSE
      dbms_output.put_line('Line 2 - a is not less than b');
   END IF;
   
   IF ( a > b ) THEN
      dbms_output.put_line('Line 3 - a is greater than b');
   ELSE
      dbms_output.put_line('Line 3 - a is not greater than b');
   END IF;

   -- Lets change value of a and b
   a := 5;
   b := 20;
   IF ( a <= b ) THEN
      dbms_output.put_line('Line 4 - a is either equal or less than b');
   END IF;

   IF ( b >= a ) THEN
      dbms_output.put_line('Line 5 - b is either equal or greater than a');
   END IF;
   
   IF ( a <> b ) THEN
      dbms_output.put_line('Line 6 - a is not equal to b');
   ELSE
      dbms_output.put_line('Line 6 - a is equal to b');
   END IF;

END;
/

當上述代碼在SQL提示符執行時,它產生了以下結果:

Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either equal or less than b
Line 5 - b is either equal or greater than a
Line 6 - a is not equal to b

PL/SQL procedure successfully completed