sql - How to Use PATINDEX or LIKE to Include Wildcards OR Beginning/End of Line? -


i'm wondering if there way avoid performing case statement or having additional criteria when isolating specific pattern, " [a-z][a-z] " can located either @ start of, middle of, or end of varchar field.

it seems though should able place wildcard (%) inside bracket create additional criteria?

the question:

does have efficient/clean solution how patindex/like include both wildcard symbol , beginning/end of line in it's results?

my specific example

in specific instance have set of messy city/state/zip address information. i'm writing query pull out state abbreviations. attempts have been successful except in instances city or zip code missing because of wildcards in patindex.

with cte  ( select 1 id,'town, fl 00012' address1 union select 2      ,'town ga, 00024'             union select 3      ,'tx 00048'                   union select 4      ,'town, ca' ) select substring(address1,nullif(1+patindex('%[ ,][a-z][a-z][ ,]%',address1),1),2) state_abbrev       ,case when address1 '[a-z][a-z][ ,]%' , address1 not '%[ ,][a-z][a-z][ ,]%' substring(address1,         patindex('[a-z][a-z][ ,]%',address1),2)             when address1 '%[ ,][a-z][a-z]' , address1 not '%[ ,][a-z][a-z][ ,]%' substring(address1,nullif(1+patindex('%[ ,][a-z][a-z]',address1),1),2)             else substring(address1,nullif(1+patindex('%[ ,][a-z][a-z][ ,]%',address1),1),2)         end state_complex       ,id,address1   cte 

which state_abbrev alias returns...

fl

ga

null

null

and state_complex returns...

fl

ga

tx

ca

you can see criteria works top 2 records have no way isolate bottom 2 without creating ridiculous case statement see in state_complex field.

as aside, yes i'm aware substring doesn't take account possible scenarios (like if string accidentally has street address rd or ln in it) understand this.

just enclose address1 in spaces or commas. if patindex, additionally correct 2 more bits, like this:

substring(address1,nullif(0+patindex('%[ ,][a-z][a-z][ ,]%',' '+address1+' '),0),2) --                        ^                                 ^^^^        ^^^^  ^ 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -