How to simulate 32-bit signed integer overflow in PL/SQL?

旧城冷巷雨未停 提交于 2019-12-06 13:01:12

问题


Do you know how to simulate a 32-bit integer overflow in Oracle PL/SQL. For instance,

2147483647 + 1 = -2147483648

or

-2147483648 - 1 = 212147483647

I tried PLS_INTEGER, but it throws an overflow exception.


回答1:


Perhaps you could trap the overflow exception, as in the following:

DECLARE 
  n PLS_INTEGER;
  addend PLS_INTEGER;

  NUMERIC_OVERFLOW EXCEPTION;
  PRAGMA EXCEPTION_INIT(NUMERIC_OVERFLOW, -1426);
BEGIN
  n := 2147483642;
  addend := 6;

  BEGIN  
    n := n + addend;
  EXCEPTION
    WHEN NUMERIC_OVERFLOW THEN
      DBMS_OUTPUT.PUT_LINE('OVERFLOW!');
      n := -2147483647 + (-2147483647 + n + addend - 1);

    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('SQLCODE=' || SQLCODE || '  ' || SQLERRM);
  END;

  DBMS_OUTPUT.PUT_LINE(n);
END;

Share and enjoy.




回答2:


I finally found a way to do that. Let say N is a value of type NUMBER, and you need to somehow simulate a 32-bit signed integer overflow, then:

N := MOD(N, 4294967296);
IF N > 2147483647
THEN
    N := N - 4294967296;
ELSIF N < -2147483648
THEN
    N := N + 4294967296;
END IF;


来源:https://stackoverflow.com/questions/10847674/how-to-simulate-32-bit-signed-integer-overflow-in-pl-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!