Proper Luhn AddCheckDigit for any length #

,

Most of the luhn scripts assume that you are working with credit-cards and then IMPROPERLY calculate their luhn check-digit by starting at the left side (assuming that the core number is always 15 digits).  However, if you don't know the length of your core number, then such an approach will fail when the length is even.  This function will work without regard to the length of the core number because it properly starts it's calculations from the right side of the number.

CREATE FUNCTION [dbo].[AddLuhnCheckDigit] (@core varchar(50) )
RETURNS int
-- =============================================
-- Author: Rempe, Bruce D. (brempe@iDataDesigns.com)
-- Create date: 10/10/2006
-- Description:	Proper Luhn check-digit calculator
-- for varying length core numbers.
--
-- =============================================
AS
	BEGIN

declare @core_wrk_char varchar(2), @core_wrk_int int, @wrk_total int, @placeholder int

SET @placeholder = LEN(@core)
SET @wrk_total = 0
 
While @placeholder > 0
Begin
 Set @core_wrk_char = SUBSTRING ( @core , @placeholder , 1 ) 
 If ((@placeholder - len(@core)) % 2) = 0
 Begin
	set @core_wrk_int = Cast(@core_wrk_char as int)
	set @core_wrk_int = @core_wrk_int * 2
	set @core_wrk_char = Cast(@core_wrk_int as varchar(2))
	if Len(@core_wrk_char) = 2
		set @wrk_total = @wrk_total + (Cast(Left(@core_wrk_char,1) as int) + Cast(Right(@core_wrk_char,1) as int))
	else
		set @wrk_total = @wrk_total + Cast(@core_wrk_char as int)
 End
 Else
 Begin
  	set @wrk_total = @wrk_total + Cast(@core_wrk_char as int)
 End
 set @placeholder = @placeholder - 1
End
 
Set @core_wrk_char = Cast(10 - Cast(Right(Cast(@wrk_total as varchar(2)),1) as int) as varchar(2))
Set @core = @core + RIGHT(RTRIM(@core_wrk_char),1)

return @core
--
-- to return only the check-digit use
-- "return right(rtrim(@core_wrk_char),1)"
-- instead.
--

END

Rate

5 (1)

Share

Share

Rate

5 (1)