ISIN Validation SQL Function

CREATE FUNCTION dbo.IsValidISIN(@ISIN NVARCHAR(12))

RETURNS INT AS BEGIN

DECLARE @Check INT

--Check digit not available

IF RIGHT(@ISIN,1) NOT BETWEEN '0' AND '9' BEGIN

 SET @Check=-1

 RETURN @Check

END


IF PATINDEX('%[^0-Z]%',@ISIN)>0 BEGIN

 SET @Check=-3

 RETURN @Check

END


DECLARE @Data NVARCHAR(30)=LEFT(@ISIN,11)

DECLARE @MultOdd INT= 1, @MultEve INT= 1

DECLARE @Sum INT=0,@StrOdd NVARCHAR(60)='',@StrEve NVARCHAR(60)=''

DECLARE @Letter INT,@Text VARCHAR(1)

SET @Letter =PATINDEX('%[A-Z]%',@Data)



SET @Text=SUBSTRING(@Data,@Letter,1) BEGIN

 WHILE @Letter>0 BEGIN

  SET @Data=STUFF(@Data,@Letter,1,ASCII(UPPER(@Text))-55)

  SET @Letter =PATINDEX('%[A-Z]%',@Data)

  SET @Text=SUBSTRING(@Data,@Letter,1)

 END

END

--Get Length Multiplier

IF LEN(@Data)%2=0 BEGIN

 SET @MultEve = 2;

END

ELSE BEGIN

SET @MultOdd = 2;

SET @Letter = 1;

END


WHILE @Letter<=LEN(@Data) BEGIN

 IF @Letter%2=1 BEGIN

  SET @StrOdd=@StrOdd+CONVERT(VARCHAR(60),CONVERT(INT,SUBSTRING(@Data,@Letter,1))*@MultOdd);

 END 

 ELSE BEGIN

  SET @StrEve=@StrEve+CONVERT(VARCHAR(60),CONVERT(INT,SUBSTRING(@Data,@Letter,1))*@MultEve);

 END

 SET @Letter=@Letter+1

END


SET @Data=@StrOdd+@StrEve

SET @Letter = 1

WHILE @Letter<=LEN(@Data) BEGIN

 SET @Sum=@Sum+CONVERT(INT,SUBSTRING(@Data,@Letter,1))

 SET @Letter=@Letter+1

END

IF LEN(@ISIN)<>12 BEGIN

 SET @Check=-4

 RETURN @Check

END

IF ISNULL(@Check,0)=0 BEGIN

 SET @Check =(SELECT (CASE WHEN RIGHT(@ISIN,1)=CONVERT(VARCHAR(1),(10-(@Sum%10))%10) THEN 1 ELSE 0 END));

END

RETURN @Check

END

GO


Comments

Popular posts from this blog

host

Steps to create SSH key from git bash

test