T-SQL function that calculates the checksum digit of a BarCo

T-SQL function that calculates the checksum digit of a BarCode
by Eli Leiba

The checksum digit algorithm for a 12-digit BarCode goes like this:

Assume the a BarCode number looks like this D1D2D3D4........D12 where Di are digits 0 to 9

sum up all the odd digits to a sum of S1
sum up all the even digit to a sum of S2
subtract S2 from S1 , do the modulu from 10 and then give the absolute positive value

The value of abs ((S1-S2)mod 10) IS the BarCode checksum digit.

Here is the suggested function code for the T-SQL BARCODE checkSum function:

Create function dbo.fn_BarCode_checkSum (@cBarcode char(12)) -- By Eli Leiba -- 08/2005 returns Int as begin declare @barCodeCheckRes Int declare @idx tinyInt declare @sgn Int set @barCodeCheckRes = 0 -- check if given Barcode is Numeric , if not return error status -1 if (IsNumeric (@cBarcode) = 0) return -1 -- check if BarCode length of number is 12 , if not return error status -2 if (Len (rtrim(ltrim(@cBarcode))) != 12) return -2 -- start the compute BarCode checksum algorithm set @idx = 1 while (@idx <= 12) begin -- Calculate sign of digit (- for even digit and + for an odd digit if ((@idx % 2) = 0) set @sgn = -1 else set @sgn = +1 set @barCodeCheckRes = @barCodeCheckRes + convert (tinyInt, substring (@cBarcode,@idx,1)) * @sgn set @idx = @idx + 1 end -- return the resulting digit, return ( abs(@barCodeCheckRes % 10)) end go


Here is an Example for the function execution for two 12 Length Barcodes:

select dbo.fn_BarCode_checkSum ('283723281122') as FirstBarc, dbo.fn_BarCode_checkSum ('123253245433') as SecondBarc

and The result:

FirstBarc SecondBarc
7 1

Lets check :

dbo.fn_BarCode_checkSum ('283723281122') = | (2 - 8 + 3 - 7 + 2 - 3 + 2 - 8 + 1 - 1 + 2 - 2)%10|
= | ( -6 -4 -1 -6 + 0 + 0)%10| = |-17 % 10| = |-7| = 7

dbo.fn_BarCode_checkSum ('123253245433') = | (1 - 2 + 3 - 2 + 5 - 3 + 2 - 4 + 5 - 4 + 3 - 3)%10| =
| (-1 + 1 + 2 - 2 + 1 + 0) %10| = |(0 + 0 + 1 + 0)%10| = |1| = 1





Remarks

Related Articles - For Members Using Check Constraints to Simulate Domains
Deployable DTS Packages
Adding Arithmetic Series sum function to SQL Server system


  Last Updated: 09/28/05 | © Mesquite Information Technologies, Inc., 2012