Need to match postcode with a region

Issue
Need to match postcode or partial postocde and return a region e.g. IP3 9SJ to 'IP3' not 'IP2'

 

Solution

DECLARE @LENGTH AS SMALLINT
DECLARE @FOUND AS NVARCHAR(10)
DECLARE @Value AS NVARCHAR(10) 

SET @LENGTH = LEN(@Value)

WHILE @LENGTH > 0 AND @FOUND IS NULL
 BEGIN
  SET @FOUND = (SELECT ukRegion from __PostcodeRegions
    WHERE SUBSTRING(@Value, 1, @LENGTH ) = ukRegion
    AND LEN(__PostcodeRegions.postcode) = @LENGTH)
  SET @LENGTH = @LENGTH -1
 END
SELECT @FOUND  AS FOUND_VALUE