With this query I get the postal code from an address and it works, but there are some cases where the address number’s length is 5 and so I get this instead of the postal code, is there any chance to get the last occurrence with PatIndex?
SELECT address,IIF((PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', address)>0), substring(address, PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', address), 5) , NULL) AS postalCode from table
Advertisement
Answer
If you want to get the LAST occurrence
- Reverse address
- Find first match
PatIndex
in reversed address - Reverse the first matching substring
Thus
SELECT address,IIF((PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', address)>0), reverse(substring(reverse(address), PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', reverse(address)), 5)) , NULL) AS postalCode from tbl