Skip to content

Instantly share code, notes, and snippets.

@simplement-e
Created April 14, 2013 12:56
Show Gist options
  • Select an option

  • Save simplement-e/5382624 to your computer and use it in GitHub Desktop.

Select an option

Save simplement-e/5382624 to your computer and use it in GitHub Desktop.
MS SQL2005+ : calcule le digit de contrôle pour un EAN13 / Compute the checksum digit for an EAN13
create function [E].[compute_ean13fromgencod](@gencod as varchar(12))
returns varchar(13)
as
begin
declare @calcul bigint, @temp int
declare @ret varchar(13)
if(len(@gencod)<>12)
return @gencod
set @calcul = 0
set @calcul = @calcul + convert(int, substring(@gencod, 12, 1))
set @calcul = @calcul + convert(int, substring(@gencod, 10, 1))
set @calcul = @calcul + convert(int, substring(@gencod, 8, 1))
set @calcul = @calcul + convert(int, substring(@gencod, 6, 1))
set @calcul = @calcul + convert(int, substring(@gencod, 4, 1))
set @calcul = @calcul + convert(int, substring(@gencod, 2, 1))
set @calcul=@calcul*3
set @temp = 0
set @temp = @temp + convert(int, substring(@gencod, 11, 1))
set @temp = @temp + convert(int, substring(@gencod, 9, 1))
set @temp = @temp + convert(int, substring(@gencod, 7, 1))
set @temp = @temp + convert(int, substring(@gencod, 5, 1))
set @temp = @temp + convert(int, substring(@gencod, 3, 1))
set @temp = @temp + convert(int, substring(@gencod, 1, 1))
set @calcul=@calcul+@temp
if(@calcul % 10) = 0
set @ret = @gencod + '0'
else
set @ret = @gencod + convert(varchar(1), 10 - (@calcul % 10))
return @ret
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment