如何使用sql server获取给定14位数字的最后一位数(第15个luhn校验位)

时间:2014-08-18 14:06:30

标签: sql sql-server-2008 tsql

我有一个14位数字,86162200359545我必须附加luhn数字才能完成。如何使用sql server获取数字。感谢。

3 个答案:

答案 0 :(得分:0)

我想最简单的方法就是: number = number * 10 + luhn

答案 1 :(得分:0)

要追加单个数字,只需乘以10并添加

DECLARE @n BIGINT = 86162200359545 
DECLARE @d INT = 0

SELECT @n * 10 + @d

计算校验位,使用数字表将字符串拆分为数字,并应用计算

DECLARE @data TABLE (id VARCHAR(15))

INSERT INTO @data (id)
VALUES ('7992739871')

SELECT luhn_id = CAST(id AS BIGINT) * 10 + d
FROM (
    SELECT id, d = SUM(CAST(CASE WHEN f > 9 THEN (f / 10) + ((f * 1.0 / 10 - 1) * 10) ELSE f END AS INT)) * 9 % 10
    FROM (
        SELECT id, f = CAST(SUBSTRING(id, n, 1) AS INT) * CASE WHEN n % 2 = 1 THEN 1 ELSE 2 END
        FROM @data
        CROSS APPLY (
            SELECT TOP (LEN(id)) n = ROW_NUMBER() OVER (ORDER BY (SELECT 1))
            FROM (SELECT 1 a UNION ALL SELECT 1 UNION ALL SELECT 1) x
            CROSS JOIN (SELECT 1 b UNION ALL SELECT 1 UNION ALL SELECT 1) y
            CROSS JOIN (SELECT 1 c UNION ALL SELECT 1 UNION ALL SELECT 1) z
        ) numbers
    ) t
    GROUP BY id
) t

答案 2 :(得分:0)

我不确定我是否正确理解了您的查询。看看以下代码是否对您有所帮助。

DECLARE @ChkDidgit INT = 0;
DECLARE @AuctualNum BIGINT = 86162200359545;


SELECT CAST((CAST(@AuctualNum AS VARCHAR) + CAST(@ChkDidgitAS VARCHAR)) AS BIGINT)