/*alter FUNCTION F_VALIDA_EAN13 (@Ean varchar(max)) RETURNS INT AS
BEGIN
    DECLARE @Factor INT
    DECLARE @Sum INT
    DECLARE @Len INT
    DECLARE @CC INT
    DECLARE @CA INT
    DECLARE @Result NVARCHAR(MAX)

    SET @Len = LEN(@Ean)
    SET @Sum = 0
    SET @Factor = 3

    IF @Len = 14 OR @Len = 13 OR @Len = 12 OR @Len = 8 
        BEGIN
            WHILE @Len > 0 
                BEGIN
                    IF @Len = 13
                        BEGIN
                            SET @Sum = @Sum + SUBSTRING(@Ean,@Len,1) * @Factor
                            SET @Factor = 4 - @Factor
                        END
                    SET @Len = @Len - 1
                END

            SET @CC = ((1000 - @Sum) % 10)
            SET @CA = SUBSTRING(@Ean,LEN(@Ean),1)

            IF  @CC = @CA
                BEGIN
                    SET @Result = 0
                END
            ELSE
                BEGIN
                    SET @Result = 1
                END
        END
    ELSE
        BEGIN
            SET @Result = 1
        END
    RETURN (@Result)
    END
*/
IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[F_VALIDA_EAN13]') AND TYPE IN (N'FN', N'IF', N'TF', N'FS', N'FT'))

DROP FUNCTION F_VALIDA_EAN13

GO

CREATE  FUNCTION F_VALIDA_EAN13(@COD_BARRAS VARCHAR(100) ) 
	RETURNS  TINYINT AS
BEGIN
DECLARE @MSOMA     MONEY
      , @I         INT
      , @Y         INT
      , @FATOR     MONEY
      , @DIG_VERIF INT
      , @DIG_CALC  INT;

SET @COD_BARRAS = RIGHT(LTRIM(RTRIM(@COD_BARRAS)), 13);

IF ISNUMERIC(@COD_BARRAS)=0
  RETURN 0

IF LEN(@COD_BARRAS) = 13
	BEGIN
		 
        SET @DIG_VERIF = RIGHT(@COD_BARRAS,1);
        SET @MSOMA = 0;
        SET @Y = 1;
        SET @I = 1; 
		
	    WHILE @I < 13
            BEGIN
                SET @MSOMA = @MSOMA + SUBSTRING(@COD_BARRAS, @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