Quote:
|
Originally Posted by RobP
We are facing an interesting problem. I want to write a casting function from char to int, that return the integer value. If the cast fails then the value 0 must be returned.
I did the following:
CREATE FUNCTION char2int(p_value varchar(100)) RETURNS INT
LANGUAGE SQL
BEGIN ATOMIC
DECLARE v_result INT;
SET RESULT = CAST(p_value AS INTEGER);
END
This function works, until a non number value is specified as input. We tried to catch this with declaring a condition fro sqlstate '22018' and define and UNDO handler.
This fails, when we create a procedure it (the error catching) works, but then I'm unable to return a result.
Is it impossible to catch errors in functions, or am I overlooking something.
Thanks,
RobP
|
I think you are going to have to write the UDf to check the parameter manually and then return accordingly. Something like this:
CREATE FUNCTION char2int(p_value varchar(100)) RETURNS INT
LANGUAGE SQL
BEGIN ATOMIC
DECLARE v_result INT;
DECLARE len int;
DECLARE cur_pos int;
DECLARE is_valid int;
DECLARE cur_char char(1);
DECLARE work_string varchar(100);
SET work_string = rtrim(ltrim(p_value));
set len = length(work_string);
set cur_pos = 1;
set is_valid = 1; -- assume it is valid
while (cur_pos <= len) do
set cur_char = substr(work_string,cur_pos,1);
IF (cur_char < '0' or cur_char > '9') then set is_valid = 0; end if;
set cur_pos = cur_pos + 1;
end while;
if (is_valid = 1)
THEN SET v_Result = integer(work_string);
else set v_Result = 0;
END IF;
return(v_Result);
END
Andy