I was recently working with a database which included a lot of serial numbers, which in some cases where IMEI numbers of phones, and I wanted to be able to identify the cases that looked like valid IMEIs.
There is some discussion of the format at http://en.wikipedia.org/wiki/IMEI. What I wanted to do was just to validate the IMEI (as opposed to IMEI/SV) format – 14 digits plus the Luhn check digit.
Here’s what I ended up with – a function to return a bit value of 1 if the supplied value is valid, and 0 if not:CREATE FUNCTION ValidIMEI(@imei varchar(24)) RETURNS bit AS
BEGIN
DECLARE @res bit
DECLARE @i int
DECLARE @digval int
DECLARE @total intSET @res = 0
SET @total = 0IF LEN(@imei) = 15 BEGIN
SET @i = 1
WHILE @i <= 14 BEGINSET @digval =
(ASCII(SUBSTRING(@imei, @i, 1)) -
ASCII('0')) * (2 - (@i % 2))
-- Double each even digit
SET @total =
@total + @digval / 10 + @digval % 10SET @i = @i + 1
ENDIF SUBSTRING(@imei, 15, 1) =
CHAR((1000 - @total) % 10 +
ASCII('0')) SET @res = 1END
RETURN(@res)
END
So, for example:
select dbo.validimei('000000000000000'), dbo.validimei('000000000000001')
returns 1 and 0 (although clearly these are unlikely to be valid IMEIs, since this just validates the length and check digit and not necessarily that the various fields of the alleged IMEI number are actually valid. Still however, it proved reasonably useful, and actually ran tolerably quickly, validation of half a million IMEIs in a few seconds.
No comments:
Post a Comment