Thursday, May 16, 2013

Check Digit Calculation


DECLARE @Temp1 INT
       ,@Temp2 INT
       ,@UPC VARCHAR(20)
       ,@CheckDigit INT;

SET @UPC = 547

SELECT @UPC = rtrim(ltrim(@UPC))
WHILE LEN(@UPC) < 11 SET @UPC = '0' + @UPC

SELECT @Temp1 = 0 +
SUBSTRING(@upc,1,1) +
SUBSTRING(@upc,3,1) +
SUBSTRING(@upc,5,1) +
SUBSTRING(@upc,7,1) +
SUBSTRING(@upc,9,1) +
SUBSTRING(@upc,11,1) 

SELECT @Temp1 = @Temp1 * 3

SELECT @Temp2 = 0 +
SUBSTRING(@upc,2,1) +
SUBSTRING(@upc,4,1) +
SUBSTRING(@upc,6,1) +
SUBSTRING(@upc,8,1) +
SUBSTRING(@upc,10,1) 

SELECT @Temp1 = @Temp1 + @Temp2

SELECT @Temp1 = (10- (@Temp1 % 10)) % 10

SELECT @CheckDigit = @Temp1

SELECT @CheckDigit

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.