Link to home
Start Free TrialLog in
Avatar of Leogal
LeogalFlag for United States of America

asked on

PATINDEX REVERSE not giving results expected

I am learning how to use PATINDEX and REVERSE together.  In this case it is a work assignment and any help given will be most appreciated.

I am attempting to pull the state out of a character string. There are two issues: 1) The state abbreviation can start in the last  position of the string or five+ positions from the end of the string.   2)  when using patindex in the attached TSQL query I am getting the first two characters of the string as opposed to the last two characters.

I am including the first 10 result records and the query itself and have blanked out all data past the state field intentionally as it is not germane to the question and to retain some anonymity to the data.

Once again, I appreciate any help given.
patinedex.rtf
sample-data.xlsx
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Leogal

ASKER

Scott, that works!  I have not used a cross apply before I will need to study more. Thanks very much for your solution.
You're welcome!

I made a couple of changes after my initial post, so be sure to refresh to make sure you get the final version.

In this case, the CROSS APPLY just allows an alias (name) to be assigned to the PATINDEX() result, so I don't have to repeat the PATINDEX() multiple times.

But the key to the logic is the '%[ ][A-Z][A-Z] %' pattern.  I've tested and verified that it should pull out state correctly even when state is followed by a zip code (as long as at least one space appears after the state).
Avatar of Leogal

ASKER

Scott, this really helped me out.