SQL服务器存储过程EAN码验证

SQL Server stored procedure EAN code validation

我需要编写一个存储过程或函数来验证 EAN 13 代码在 SQL 服务器中的插入。

谁能帮帮我?

已解决,

我创建了一个验证函数:

CREATE FUNCTION [sp_ean](@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

结果: 0true1false

谢谢!

也许你会发现这样的东西更干净。它处理可变长度输入,并且还具有可用作检查约束的优点,如 Joe Celko.

所指出的
CASE WHEN CAST(SUBSTRING(REVERSE(ean), 1, 1) AS INTEGER) =
        10 - (
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 2, 1)) AS INT)
               1 * CAST(SUBSTRING(REVERSE(ean) + '000000', 3, 1)) AS INT)
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 4, 1)) AS INT)
               1 * CAST(SUBSTRING(REVERSE(ean) + '000000', 5, 1)) AS INT)
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 6, 1)) AS INT)
               1 * CAST(SUBSTRING(REVERSE(ean) + '000000', 7, 1)) AS INT)
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 8, 1)) AS INT)
               1 * CAST(SUBSTRING(REVERSE(ean) + '000000', 9, 1)) AS INT)
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 10, 1)) AS INT)
               1 * CAST(SUBSTRING(REVERSE(ean) + '000000', 11, 1)) AS INT)
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 12, 1)) AS INT)
               1 * CAST(SUBSTRING(REVERSE(ean) + '000000', 13, 1)) AS INT)
               3 * CAST(SUBSTRING(REVERSE(ean) + '000000', 14, 1)) AS INT)
             ) % 10
THEN 1 ELSE 0 END