CREATE OR ALTER FUNCTION dbo.Luhn10
(
        @Data VARCHAR(MAX)
)
RETURNS TABLE
AS
RETURN  SELECT  SUM(CASE WHEN n >= 10 THEN 9 - n % 10 ELSE 10 - n END) % 10 AS CheckDigit
        FROM    (
                        SELECT  ((1 + LEN(@Data) - n) % 2 + 1) * SUBSTRING(@Data, n, 1) AS n
                        FROM    dbo.numbers
                        WHERE   n BETWEEN 1 AND LEN(@Data)
                                AND LEN(@Data) <= 1000  -- Arbitrary maximum length
                                AND @Data NOT LIKE '%[^0123456789]%'
                ) AS f;
