This a solution Luhn algorithm for credit validation.
This algorithm is a basic one inspired by wikipedia. I mean no check for length, type, and so on. You can enhance the base code as you want it to be.
The listing code of the following fucntion is tested on MSSQL 2012:
IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
BEGIN
DROP FUNCTION dbo.LuhnALGValidation
IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
PRINT '<<< FAILED DROPPING FUNCTION dbo.LuhnALGValidation >>>'
ELSE
PRINT '<<< DROPPED FUNCTION dbo.LuhnALGValidation >>>'
END
go
CREATE FUNCTION dbo.LuhnALGValidation
(
@Luhn VARCHAR(8000)
)
RETURNS BIT
AS
BEGIN
IF @Luhn LIKE '%[^0-9]%'
RETURN 0
DECLARE @Index SMALLINT,
@Multiplier TINYINT,
@Sum INT,
@Flag INT,
@temp TINYINT,
@Plus TINYINT
SELECT @Index = LEN(@Luhn),
@Multiplier = 1,
@Flag = 0,
@Sum = 0
WHILE @Index >= 1
BEGIN
SELECT @temp = CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
IF @Flag = 1
BEGIN
SELECT @temp = 2 * CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
IF @temp > 9
BEGIN
SELECT @temp = @temp - 9
END
END
SELECT @Sum = @Sum + @temp
IF @Flag = 1
SELECT @Flag = 0
ELSE
SELECT @Flag = 1
SELECT @Index = @Index - 1
END
RETURN CASE WHEN @Sum % 10 = 0 THEN 1 ELSE 0 END
END
go
IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
PRINT '<<< CREATED FUNCTION dbo.LuhnALGValidation >>>'
ELSE
PRINT '<<< FAILED CREATING FUNCTION dbo.LuhnALGValidation >>>'
go
I want it to work in database side. No matter in performance.
If you can help me to enhance this code.