IF EXISTS (  SELECT * 
              FROM sys.objects 
             WHERE object_id = OBJECT_ID(N'[dbo].[sp_valida_ean13]') 
               AND type IN (N'FN')  )
DROP FUNCTION sp_valida_ean13;

GO
CREATE FUNCTION [dbo].[sp_valida_ean13](@number varchar(max)) RETURNS smallint AS
BEGIN
 DECLARE @MSOMA     MONEY
      , @I         INT
      , @Y         INT
      , @FATOR     MONEY
      , @DIG_VERIF INT
      , @DIG_CALC  INT;
SET @number = RIGHT(LTRIM(RTRIM(@number)), 13);
IF ISNUMERIC(@number)=0
  RETURN 0
IF LEN(@number) = 13
	BEGIN
        SET @DIG_VERIF = RIGHT(@number,1);
        SET @MSOMA = 0;
        SET @Y = 1;
        SET @I = 1; 
	    WHILE @I < 13
            BEGIN
                SET @MSOMA = @MSOMA + SUBSTRING(@number, @I, 1) * @Y;
                IF @Y = 1
                    SET @Y = 3;
                    ELSE
                SET @Y = 1;
                SET @I = @I + 1;
            END;
		SET @FATOR =  ROUND((@MSOMA / 10),0,1) + 1;
        SET @DIG_CALC = (@FATOR * 10) - @MSOMA;
	    IF @DIG_CALC = 10
            SET @DIG_CALC = 0;
        IF @DIG_VERIF <> @DIG_CALC
            RETURN 0
    END
ELSE
	BEGIN
		RETURN 0
	END;
	RETURN 1
END