
convert the to a fixed width char datatype Let's now set up the function header, and put in a couple of simple constraints - the function can accept a string no longer than 20 characters, and if there aren't at least three digits present in the string, return an error code: Luckily we can combine this and use a temporary table variable both for cleansing the number and for validity checking. In the real world, we'll receive a number for testing as a string, or VARCHAR of indeterminate length, so we'll work on this basis rather than using an INT/BIGINT. We must also cleanse the card number and make sure we don't have any trailing spaces. What we CAN do, however, is use a temporary table variable to the same effect. So whereas in Python or C we might implement the card number as an array of numbers then apply transformations to all elements of the array, we don't have that luxury in SQL Server.
REAL CREDIT CARD VALIDATOR CODE
The code we write must be fairly efficient, but we're constrained in a unique way by using T-SQL - we're writing in the language of relational set theory, not in object oriented language. Let's now turn our attention to rewriting this in T-SQL. The number we will use is an AMEX sample card number: Let's first get a number which we are testing for validity and split it out into its component digits, in a format we can easily understand. Stage 1: N * 2 for every 2nd N from the right All stages are carried out using simple mathematics and rules. The algorithm can be broken down into 4 stages. The samples are from PayPal and may be found here: Algorithm Overview
REAL CREDIT CARD VALIDATOR MOD
One final note - any card numbers used here for illustration / example are fictitious - these pass the MOD 10 check, but are not real credit card numbers, only samples. I will also show you a method to remove 'noise' from the number - for example, spaces or leading/trailing characters.

In the following sections I will provide a step-by-step guide to validating these numbers by hand, then show how we can replicate this as a User-Defined Function (UDF) within SQL Server.

In the Next Steps section at the end of this tip. Luhn's Algorithm, links for which are provided It has no cryptographic validity, but it is a useful rule-of-thumb check that can be used to validate that a card number is correct, and can be used in its opposite form to generate account (and credit card) numbers - to help discourage potential fraudsters, this function is NOT covered here.

The industry standard for checking credit card numbers for validity is known in colloquial terms as the 'MOD 10 Check', or more formally as Luhn's Algorithm.
