Hi,
Normally, every Visa/Master card have the 16 digits number printed(embossed) on the card. Last 16th digit is called as check digit.
There is an algorithm called
MOD10 to verify that card number is valid or not. Here I am providing a link for detailed description about check digits logic:
Cards Check Digits[
^]
I am providing a SQL Server function for 'Check Digit' for Visa/Master Cards(16 Digits).
CREATE FUNCTION [DBO].[MOD10CHECKDIGIT](@STR VARCHAR(15))
RETURNS VARCHAR(1)
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @RETURNSTR VARCHAR(100);
DECLARE @REVERSESTR VARCHAR(15);
DECLARE @CNT INT;
DECLARE @SUMVAL INT;
DECLARE @TEMPVAL INT;
DECLARE @TEMPVAL1 INT;
IF(LEN(@STR)<>15)
SET @RETURNSTR='NO';
ELSE
BEGIN
SET @REVERSESTR = REVERSE(@STR);
SET @SUMVAL=0;
SET @CNT=1;
WHILE @CNT < 16
BEGIN
SET @TEMPVAL =0;
SET @TEMPVAL1 =0;
IF((@CNT%2)<>0)
SET @TEMPVAL = (CONVERT(INT,SUBSTRING(@REVERSESTR,@CNT,1) * 2));
ELSE
SET @TEMPVAL = (CONVERT(INT,SUBSTRING(@REVERSESTR,@CNT,1)));
IF(@TEMPVAL>9)
BEGIN
SET @TEMPVAL1 = CONVERT(INT,SUBSTRING(CONVERT(VARCHAR,@TEMPVAL),1,1)) +
CONVERT(INT,SUBSTRING(CONVERT(VARCHAR,@TEMPVAL),2,1));
SET @TEMPVAL=@TEMPVAL1;
END;
SET @SUMVAL = @SUMVAL + @TEMPVAL;
SET @CNT= @CNT + 1;
END
SET @RETURNSTR=CONVERT(VARCHAR,(10 - (@SUMVAL%10)));
END
RETURN @RETURNSTR;
END
Note: Every VISA card starts with digit "4" and Mastercard stats with "5".