Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How do i split strings. In one field i have a data of city state and zip

e.g:-
Address3 contains

Florida fl 40005
los angeles al 50066

I need to split address3 into City florida state fl and zip - 40006

I have tried using substring and charindex but in los angeles my logic gets wrong.

Can anyone help ?

Thanks in advance..

What I have tried:

select SUBSTRING(@address3,1,charindex(' ',@address3))
Go--
florida
los -- this gets wrong
Posted
Updated 5-Sep-18 21:31pm
Comments
RedDk 5-Sep-18 21:22pm    
Both of those returns are correct. The best reference to use in any case is the Book-on-line help that ships with SSMSE. You don't even have to look anything up. Put your cursor on the KEYWORD "SUBSTRING" hit F1 and you've got half a dozen examples showing what is proper. Down under the F1 object then there's a host of related terms and methods and functions. This is the best course of action. Frankly, this question is silly.

 
Share this answer
 
v2
Comments
CHill60 6-Sep-18 3:57am    
Don't forget from SQL 2016 onwards there is also STRING_SPLIT (Transact-SQL) | Microsoft Docs[^] although they'd still have to be clever with realising they still need to start at the end to handle spaces in the city name :-)
Maciej Los 6-Sep-18 4:03am    
Goog point, Caroline! Thanks :)
Based on the sample data, the assumption is the address format always the same. I would suggest to use PATHINDEX + expression + RIGHT + REVERSE functions to manipulate the string. See below example. To find the city name, use the substring from position 0 to position of the state abbreviation.

To find the state position, assume that the state will always start with a space, then two characters, follow by a space and then follow by a number. etc...

SQL
DECLARE @table1 TABLE (
	Address1	VARCHAR(50)
)

INSERT INTO @table1
	SELECT 'Florida fl 40005' UNION
	SELECT 'los angeles al 50066' UNION
	SELECT ' EL Paso TX 79901'

SELECT  
City = SUBSTRING(Address1, 0, PATINDEX('%[ ][a-z][a-z][ ][1-9]%',Address1)),
[State] = SUBSTRING(Address1, PATINDEX('%[ ][a-z][a-z][ ][1-9]%',Address1), 3),
Zip = RIGHT(Address1, CHARINDEX(' ', REVERSE(Address1)) - 1) FROM @table1

Output:
City	        State	Zip
 EL Paso	     TX	    79901
Florida	         fl	    40005
los angeles	     al	    50066
 
Share this answer
 
Comments
Maciej Los 6-Sep-18 3:22am    
5ed!
Bryian Tan 6-Sep-18 9:35am    
thanks :)
CHill60 6-Sep-18 3:55am    
Also 5'd. Why would someone give this a 1-vote?
Bryian Tan 6-Sep-18 9:35am    
thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900