Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Select query part of postcode

Author  Topic 

SNandra
Starting Member

4 Posts

Posted - 2008-02-25 : 04:31:25
Hi

I have a set of postcodes in mtable eg

Codes
AB1 4AB
ABC1 4AB
DE23 4ff
B1 3RR
B24 3RR

I want to create a select query which just picks up the first part of the postcodes. Eg:

AB1
ABC1
DE23
B1
B24

Any ideas?

ayamas
Aged Yak Warrior

552 Posts

Posted - 2008-02-25 : 04:47:39
declare @str varchar(50)
set @str ='AB1 4AB'
select substring(@str,1,charindex(' ',@str))
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-02-25 : 05:05:02
or SELECT CASE WHEN CHARINDEX(' ',Codes) >0
THEN LEFT(Codes,CHARINDEX(' ',Codes)-1)
ELSE Codes
END
Go to Top of Page

SNandra
Starting Member

4 Posts

Posted - 2008-02-25 : 05:20:03
Cheers

I went with this in the end

Select SUBSTRING(Codes, 1, CHARINDEX(' ', Codes)) as PartPostCode
FROM PostCodes

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-02-25 : 06:00:05
quote:
Originally posted by SNandra

Cheers

I went with this in the end

Select SUBSTRING(Codes, 1, CHARINDEX(' ', Codes)) as PartPostCode
FROM PostCodes





or

Select PARSENAME(REPLACE(codes,' ','.'),2) as PartPostCode
FROM PostCodes

provided codes has only two parts

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SNandra
Starting Member

4 Posts

Posted - 2008-02-25 : 06:04:08
Yes that works too.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-02-25 : 06:06:48
quote:
Originally posted by SNandra

Yes that works too.


There can be N number of methods for string manipulation

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -