-1

我需要编写一个存储过程或函数来验证 EAN13 代码在 SQL Server 中的插入。

谁能帮我?

4

2 回答 2

0

解决,

我创建了一个验证函数:

CREATE FUNCTION [sp_ean](@Ean varchar(max)) RETURNS INT AS
开始
    声明@Factor INT
    声明 @Sum INT
    声明@Len INT
    声明@CC INT
    声明@CA INT
    声明@Result NVARCHAR(MAX)

    SET @Len = LEN(@Ean)
    SET @Sum = 0
    设置@因子 = 3

    如果 @Len = 14 或 @Len = 13 或 @Len = 12 或 @Len = 8
        开始
            而@Len > 0
                开始
                    如果@Len 13
                        开始
                            SET @Sum = @Sum + SUBSTRING(@Ean,@Len,1) * @Factor
                            SET @Factor = 4 - @Factor
                        结尾
                    设置@Len = @Len - 1
                结尾

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

            如果@CC = @CA
                开始
                    设置@结果 = 0
                结尾
            别的
                开始
                    设置@Result = 1
                结尾
        结尾
    别的
        开始
            设置@Result = 1
        结尾
    返回(@Result)
    结尾

结果: 01

谢谢!

于 2015-03-20T17:22:01.763 回答
0

也许你会发现这样的东西更干净。它处理可变长度输入,并且还具有可用作检查约束的优点,正如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
于 2015-03-20T17:49:37.140 回答