Here is a suggestion. Consider implementing this functionality as a User Defined Functions (or UDF). This will allow you to write code in either c
or c++
rather than SQL
.
Alternatively, You can use REGEXP support in MySQL.
This is a solution for Part 1 of your question:
This example is for validating an IPV4
address using REGEXP
SELECT '123.1.2.3'
REGEXP '^([1-9]|[1-9][0-9]|1[013-9][0-9]|12[0-689]|2[0-4][1-9]|25[0-4])\.(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][1-9]|25[0-4])$'
;
SQL Fiddle Link
(Note: I have never used triggers myself. Hence cannot give you ready-to-use code. But you can use this example to make a trigger out of it)
I think solution for part 2 is a simple find-and-replace. Here again a REGEXP can be used to match all the patterns of 0
, 00
, .0
, .00
and replace with a .
(or nothing, if beginning of string)
Update 2:
Here is an SQL example to remove leading zeros. I did not have to use REGEXP here since CAST()
did the magic!
SELECT ip,
CONCAT_WS('.',CAST(SUBSTRING_INDEX(ip,'.',1) as UNSIGNED),
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',2),'.',-1) as UNSIGNED),
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-2),'.',1) as UNSIGNED),
CAST(SUBSTRING_INDEX(ip,'.',-1) as UNSIGNED)) as Converted_IP
FROM ip_addr;
If ip_addr
is a table with a column named ip
and values like this
-------------
IP
-------------
127.0.0.1
001.02.0.123
1.23.123.000
-------------
The SQL
will Output:
-----------------------------
IP CONVERTED_IP
-----------------------------
127.0.0.1 127.0.0.1
001.02.0.123 1.2.0.123
1.23.123.000 1.23.123.0
-----------------------------
SQL Fiddle Link
Update 3:
I think this solution by Michael Berkowski is awesome