Click here to Skip to main content
15,911,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a column name City whose data is containing spl characters and space.
Ex.:My Table
1. Ahmedabad - CG Road
2. Ahmedabad-Satellite Road
2. Delhi - Malviya Nagar
3. Hyderabad - Kukatpally

I want to retrieve the data as per my output.
OutPut:
1. col1 =Ahmedabad
col2 = CG Road
2. col1 =Ahmedabad
col2 = Satellite Road
3. col1 =Delhi
col2 = Malviya Nagar
4. col1 =Hyderabad
col2 = Kukatpally

Please help me out in my query.
Here is my query which i tried to work but unable to display as required.

CASE
WHEN City LIKE '%-%' THEN LEFT(City, Charindex(' ', City) - 1) ELSE City
END as CityName,
CASE
WHEN City LIKE '%-%' THEN RIGHT(City, Charindex(' ', Reverse(City)) -1)
END as CityLocation


--
Thanks in Advance :)
Posted

Hi, please run this sql query , this will gives you the required output surely.

Thanks in advance


SQL
SELECT substring(City, 1, CHARINDEX('-',City)-1) CityName,
substring(City, CHARINDEX('-',City)+1, LEN(City)) CityLocation
FROM My_Table
 
Share this answer
 
Comments
pn46 18-Jun-15 7:44am    
Hi Mr.deepankarbhatnagar,
Thank you for the help. But unfortunately i encountered with the below error.

Msg 537, Level 16, State 2, Line 2
Invalid length parameter passed to the LEFT or SUBSTRING function.
Change the ' ' to '-':
SQL
SELECT
CASE WHEN City LIKE '%-%' THEN LEFT(City, Charindex('-', City) - 1) ELSE City END as CityName,
CASE WHEN City LIKE '%-%' THEN RIGHT(City, Charindex('-', Reverse(City)) -1) END as CityLocation
FROM Addresses
 
Share this answer
 
Comments
pn46 18-Jun-15 7:44am    
Thanks a ton for the help. :)
OriginalGriff 18-Jun-15 7:46am    
You're welcome!
hi,

Use this one


SQL
SELECT city,
       Substring(city, 1, Charindex('-', city, 1) - 1)     AS col1,
       Substring(city, Charindex('-', city, 1)+1, Len(city)) AS col2
FROM   cp_locations_D_D



Thanks
Dhamu
 
Share this answer
 
Comments
Dhamodharan A 19-Jun-15 4:22am    
May i know why you down voted my answer ,whats wrong on that ???

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