Monday, 14 January 2013

DB2 implementation of INET_ATON MySQL function

Here's a sample implementation of MySQL INET_ATON function in DB2. If you are going to use this solution, you may need to ensure that valid values are passed. It doesn't make any validation of the input data provided.

CREATE OR REPLACE FUNCTION INET_ATON (ip varchar(16))
 RETURNS integer
 LANGUAGE SQL
 DETERMINISTIC
 NO EXTERNAL ACTION


BEGIN ATOMIC
DECLARE a, b, c, d Integer default 0;
DECLARE N integer default 0;
declare x varchar(16);

 set x = ip;

 set a = substr(x, 1, locate('.', x));
 set x = substr(x, locate('.', x) + 1);
 set b = substr(x, 1, locate('.', x));
 set x = substr(x, locate('.', x) + 1);
 set c = substr(x, 1, locate('.', x));
 set x = substr(x, locate('.', x) + 1);
 set d = substr(x, 1);
 set N = a * power(2, 24) + b * power(2, 16) + c * power(2, 8) + d;

 return N;
END


No comments:

Post a Comment