第一次实际发布在这里。虽然从阅读帖子中学到了很多东西!我的问题:尝试制作一个随机的加拿大SIN发生器来自动化一些客户测试帐户插入。我不希望通过函数执行此操作,希望它可以在一个查询中执行,以便稍后调用它。
我试图将CheckDigit附加到SIN的后面。所以@SIN + CheckDigit结果。非常感谢任何帮助!
我得到的当前示例结果是 检查数字 2 罪 28111173
DECLARE @SIN int
SET @SIN= (SELECT FLOOR(RAND()*(81091888-13323110)+13323110))
DECLARE @IMEI int = @SIN; -- Check digit(last digit)
WITH SINVerify (n) AS
(
SELECT TOP (LEN(@IMEI))
ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0)) a(n)
)
--Luhn algorithm
(SELECT CheckDigit=9*SUM(SumOfDigits)%10
FROM SINVerify a
CROSS APPLY
(
SELECT [Digit*Multiplier] = (1+n%2) * SUBSTRING(REVERSE(@IMEI), n, 1)
) b
CROSS APPLY
(
SELECT SumOfDigits = [Digit*Multiplier]%10 + [Digit*Multiplier]/10
) c)
(SELECT @SIN AS 'SIN')
答案 0 :(得分:0)
select cast(@sin as char(10)) + cast(@checkdigit as char(1)) as SIN
答案 1 :(得分:0)
对我来说,你可以压缩这一点,并在那里删除一些不必要的复杂性:
-- testing
select sin, (n % 2 + 1) as weight, sin / cast(power(10, n) as int) % 10 as digit
from
(select cast(floor(rand()*(81091888-13323110)+13323110) as int)) s(sin)
cross apply
(values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) a(n);
-- final output
select sum((n % 2 + 1) * (sin / cast(power(10, n) as int) % 10)) % 10 as checkdigit
from
(select cast(floor(rand()*(81091888-13323110)+13323110) as int)) s(sin)
cross apply
(values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) a(n);