Question

I want to separate city name from the addresses in the Data base.

addresses are in different formats e.g

835 street no.3  Jalabad D.I. Khan ................ here city name is D.I khan
Ho. No. 102 St. No. 85  RawalPindi   ..........here city name is RawalPindi
h no.944 St. No.74  Karkhana road Gujrat   ......here city name is Gujrat
Ho. no.241 S No.26  I-8/3 Isb              .........here city name is isb

I am doing this but it is only working for few... I need a general query which can work for every format of address

SELECT DISTINCT REVERSE
( 
  LEFT( REVERSE(All_Students.Address), CHARINDEX(' ', REVERSE(All_Students.Address))-1 ) 
) as Addresses
from All_Students
order by addresses
Was it helpful?

Solution

What do we know about Cities in these address strings? City is in the end of the string but it can contain more than 1 word. So I think there is no way to formalize a method to cut a City name from the Address line using only this table.

I think the one way to do it is to find an universal City table for your area/country in the Internet for example in any format (ZIP codes, government statistics,...) and use this table to cut Cities from this table from the Address line.

For MySQL

SELECT TRIM(TRIM(TRAILING Cities.Name FROM Address) ), Cities.Name
from All_Students left join Cities 
     on All_Students.Address like CONCAT('% ',Cities.Name)

For MS SQL Server

SELECT LEFT(Address,LEN(Address)-LEN(Cities.Name)), Cities.Name
from All_Students left join Cities 
     on All_Students.Address like '% '+Cities.Name

To update in MS SQL as required in the comment use this :

UPDATE
    A
SET
    A.address = B.NewAddress,
    A.City = B.City
FROM
    Transformed_All_Student A
    JOIN
    (
      SELECT Student_id, 
             LEFT(Address,LEN(Address)-LEN(Cities.Name)) as NewAddress, 
             Cities.Name as City
      from All_Students left join Cities 
         on All_Students.Address like '% '+Cities.Name

    ) B 
ON A.Student_ID = B.Student_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top