teisipäev, 29. märts 2016

Eesti isikukoodi kontrollsumma arvutamise funktsioon Transact-SQL

-- =============================================
-- Author: Kuido Külm
-- Description: Arvutab Eesti isikukoodi kontrollsumma
-- =============================================
CREATE FUNCTION [dbo].[EST_PERSON_IDCODE_CHECKSUM_S](@isikukood NVARCHAR(11))
RETURNS NVARCHAR(1)
AS
BEGIN
DECLARE  @checksum INT = -1, @sum INT=0, @weight INT=1, @i INT=1,@k INT
WHILE @i <= 10
BEGIN
    SET @k=CAST(SUBSTRING(@isikukood,@i,1) AS INT)*@weight
SET @sum=@sum+@k
IF @weight = 9
 SET @weight=1
ELSE
 SET @weight=@weight+1
SET @i=@i+1
END
SET @checksum=@sum%11
IF @checksum != 10
  RETURN CAST(@checksum AS NVARCHAR(1))

SET @sum=0
SET @weight=3
SET @i=1
WHILE @i <= 10
BEGIN
    SET @k=CAST(SUBSTRING(@isikukood,@i,1) AS INT)*@weight
SET @sum=@sum+@k
IF @weight = 9
 SET @weight=1
ELSE
 SET @weight=@weight+1
SET @i=@i+1
END
SET @checksum=@sum%11
IF @checksum != 10
  RETURN CAST(@checksum AS NVARCHAR(1))

RETURN '0'
END