postgresql - SQL Complex number constraint -
hello using postegresql , want constrain number(tax id number) obey following rules:
- 9 digits
- the last digit (z) calculated according to:
x = 8th * 2 + 7th * 3 + 6th * 4 + 5th * 5 + 4th * 6 + 3rd * 7 + 2nd * 8 + 1st + 9
y = x % 11 if (y == 0 || x == 1) z = 0; else z = 11 - y is possible in sql?
yes, possible although cumbersome. looks this:
check ((col regexp_matches '^[0-9]{9}$) , (case when (substring(col, 1, 1) * 9 + substring(col, 2, 1) * 8 + substring(col, 3, 1) * 7 + substring(col, 4, 1) * 6 + substring(col, 5, 1) * 5 + substring(col, 6, 1) * 4 + substring(col, 7, 1) * 3 + substring(col, 8, 1) * 2 ) % 11 = 0 or (substring(col, 1, 1) * 9 + substring(col, 2, 1) * 8 + substring(col, 3, 1) * 7 + substring(col, 4, 1) * 6 + substring(col, 5, 1) * 5 + substring(col, 6, 1) * 4 + substring(col, 7, 1) * 3 + substring(col, 8, 1) * 2 ) = 1 0 else 11 - ((substring(col, 1, 1) * 9 + substring(col, 2, 1) * 8 + substring(col, 3, 1) * 7 + substring(col, 4, 1) * 6 + substring(col, 5, 1) * 5 + substring(col, 6, 1) * 4 + substring(col, 7, 1) * 3 + substring(col, 8, 1) * 2 ) % 11 ) end) = substring(col, 9, 1) + 0 ) personally, encapsulate in function , use function instead.
Comments
Post a Comment