1

I have some data like below:

W2 2JP 
W14 9NF 
W1K 5PE 
W1K 5PE 
SW7 5EU 
W1K 5PE 
N2 9QB

I would like to have output like:

W2
W14
W1
W1
SW7
W1
N2

Any help or direction appreciated, I can find and replace to where I get everthing to left of ' ' but I cannot then exclude the letter at the end of the first half of postcode

finngeraghty
  • 107
  • 1
  • 8

1 Answers1

1

You can sue SUBSTRING and CHARINDEX

WITH cte(UKPostCodes) AS
(
SELECT 'W2 2JP' UNION ALL
SELECT 'W14 9NF' UNION ALL
SELECT 'W1K 5PE' UNION ALL
SELECT 'W1K 5PE' UNION ALL
SELECT 'SW7 5EU' UNION ALL
SELECT 'W1K 5PE' UNION ALL
SELECT 'N2 9QB'
)
SELECT CASE WHEN SUBSTRING(SUBSTRING(UKPostCodes,1,CHARINDEX(' ',UKPostCodes)-1),3,1) LIKE '[a-zA-z]'
          THEN SUBSTRING(SUBSTRING(UKPostCodes,1,CHARINDEX(' ',UKPostCodes)-1),1,2)
          ELSE SUBSTRING(UKPostCodes,1,CHARINDEX(' ',UKPostCodes)-1)
      END
FROM cte
Gouri Shankar Aechoor
  • 1,561
  • 1
  • 8
  • 8