I have an address field where all the address details are held in one column, I want to create some labels so need to be able to split the address into the correct format. Example :-
ADDRESS
PIKE ROAD, AL 36064-3401
MEMPHIS TN 38104-5802
JAMAICA PLAIN MA 02130-2337
Need to split this column into
City State Zip
PIKE ROAD AL 36064-3401
MEMPHIS TN 38104-5802
JAMAICA PLAIN MA 02130-2337
I am able to extract Zip code using
STUFF(Address, 1, Len(Address) +1- CHARINDEX(' ',Reverse(Address)), '') from abx
but I am having trouble in extracting city and state. Is it possible to split the string based on the length of words, i.e. all the Characters before the length of the word (2) goes in City and all the words with 2 characters goes in state example: - Pike Road goes into the City and AL (length is 2) in the state?
4条答案
按热度按时间ecfsfe2w1#
This works for these three examples. As @Kevin pointed out above, this works if your data is consistent, which is, as he said, "a very big if."
What I did was create a subquery mimicking a table. It has one column, "x", that just has a string value. I worked backwards to get the zip code first (which you figured out), then the state, then the street address. The function(s) used to extract each piece of information build upon the previous one.
I haven't used SQL Server in years, so I used a web app designed to mimick SQL Server 2014 .
This query should produce the table in the screenshot below:
HTH!
Cheers,
-Maashu
raogr8fs2#
You can do something like this, and it will work if your data is consistent. That is a very big IF...
OUTPUT:
jdgnovmf3#
As @Habo said, you only need to use
LEN
andSUBSTRING
.ovfsdjhp4#
If your data is consistent and delimited, you may use the following:
The above table has a column that have values of "steet, city, state" per row. Please look at www.mssqltips.com for the entire explanation and examples.