Catch exception in DB2 function
Question
I want to catch exception in DB2 function and return 0 if there was an exception. I don't know how the right syntax
create function is_decimal(c_data varchar(100))
RETURNS INTEGER
begin
select cast(c_data as decimal(12,10)) from sysibm.sysdummy1;
return 1;
DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING
return 0;
end
Solution
Like @mustaccio pointed out, you need to select into something, and you need to declare the handler before the actual code. Something like:
create or replace function is_decimal(c_data varchar(100))
RETURNS INTEGER
begin
declare t decimal(12,10);
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION, SQLWARNING BEGIN return 0; END;
select cast(c_data as decimal(12,10)) into t from sysibm.sysdummy1;
return 1;
end @
should work. I used @ as a statement terminator
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange