Peter Larsson Blog

Patron Saint of Lost Yaks

How to check Finnish personal number

CREATE FUNCTION dbo.fnCheckFinSSN
(
            @SSN CHAR(11)
)
RETURNS BIT
AS
BEGIN
    IF LOWER(@SSN) NOT LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][-+a][0-9][0-9][0-9][0-9a-y]'
        RETURN 0
 
    IF SUBSTRING(@SSN, 7, 1) IN('-', '+') AND ISDATE('19' + SUBSTRING(@SSN, 1, 6)) = 0
        RETURN 0
 
    IF LOWER(SUBSTRING(@SSN, 7, 1)) = 'a' AND ISDATE('20' + SUBSTRING(@SSN, 1, 6)) = 0
        RETURN 0
 
    DECLARE @Digits INT
 
    SET     @Digits = CAST(SUBSTRING(@SSN, 1, 6) + SUBSTRING(@SSN, 8, 3) AS INT) % 31
 
    IF SUBSTRING('0123456789abcdefghijklmnopqrstuvwxy', @Digits + 1, 1) <> LOWER(RIGHT(@SSN, 1))
        SET @Digits = -1
 
    RETURN @Digits + 1
END