Skip to content
Advertisement

T-SQL :: generate random Swiss National Identification Number (AHV/AVS)

I woul like to generate random Swiss National Identification Number (AHV/AVS).

I found a website that can do that and if I look at the source code of the same page I can alos see the JavaScript code that can generate it.

The numbers are generated following this pattern:

enter image description here

  1. 756: is the prefix number, it never changes
  2. 1234: is a random number
  3. 5678: is a random number
  4. 9: is a random number
  5. 7: is the control number that is generated by this calculation:
    • Starting at the first number, take every other number and sum them: 7 + 6 + 2 + 4 + 6 + 8 = 33
    • Starting at the drcond number, take every other number and sum them: 5 + 1 + 3 + 5 + 7 + 9 = 30
    • Then multiply the second number x 3 and sum the first number: 33 + (30 x 3) = 123
    • Now make 10 minus the modulo of that number: 10-(123%10) = 10-3 = 7

===> And this is how we finally have obtained 7 which is the last number <===

I have created a SQL command that can generate the random number I need:

This code generates all random numbers that I need but I’m missing how to select one number out of two.

I don’t know if T-SQL can parse numbers and select one out of two.

Advertisement

Answer

This implementation uses integer calculations instead of substring to get digits.

Note: I have added %10 to the final result of check digit calculation to convert 10 -> 0.

Result

Update

Checked the return value of random number generator expression and found that it can return a 5 digit value i.e. 10000.

To fix it you need to remove “+ 1”:

User contributions licensed under: CC BY-SA
11 People found this is helpful
Advertisement