Monday, March 12, 2012

PL/SQL Exponentiation

(Tested on Oracle 11.) You can use ** in PL/SQL to do exponentiation: 

SQL> set serveroutput on
SQL> declare
  2  a number := 8**0.5;
  3  begin
  4  dbms_output.put_line('a = '||a);
  5  end;
  6  /
a = 2.82842712474619009760337744841939615716

PL/SQL procedure successfully completed.

SQL>

The order of precedence seems strange as exponentiation is done before unary minus. I think that -2**2 should be 4, not -4. Of course, you can use brackets to change the order of precedence, if you wish:

SQL> declare
  2  b number := -2**2;
  3  c number := (-2)**2;
  4  begin
  5  dbms_output.put_line('b = '||b);
  6  dbms_output.put_line('c = '||c);
  7  end;
  8  /
b = -4
c = 4

PL/SQL procedure successfully completed.

SQL>

No comments:

Post a Comment