I have a requirement to retrieve a nominal ledger code based on the postcode sector of a delivery postcode in a contract. (The UK Postcode Sector is the single digit after the space, so for SL9 1DY, I need SL9 1). I have a query which extracts the postcode up to the sector from the delivery address on the contract. But I need to use this result to join to the table that holds the nominal code for that postcode sector and return the NLCC:
This is what I'm aiming for:
 +--------+----------+------+
| CONTNO | DELPCODE | NLCC |
+--------+----------+------+
| 300015 | SL9 0LY  |   17 |
| 300138 | SL6 1NF  |   14 |
| 300412 | SL6 5LL  |   14 |
| 300573 | SL6 2PL  |   14 |
| 300696 | SL0 9JQ  |   17 |
| 300764 | SL5 7EQ  |   14 |
+--------+----------+------+
The very simplified Contracts table can be built like this:
CREATE TABLE #CONTRACTS (CONTNO varchar(10), DELPCODE varchar(10));
INSERT INTO #Contracts (CONTNO, DELPCODE) VALUES ('300015','SL9 0LY');
INSERT INTO #Contracts (CONTNO, DELPCODE) VALUES ('300138','SL6 1NF');
INSERT INTO #Contracts (CONTNO, DELPCODE) VALUES ('300412','SL6 5LL');
INSERT INTO #Contracts (CONTNO, DELPCODE) VALUES ('300573','SL6 2PL');
INSERT INTO #Contracts (CONTNO, DELPCODE) VALUES ('300696','SL0 9JQ');
INSERT INTO #Contracts (CONTNO, DELPCODE) VALUES ('300764','SL5 7EQ');
This script creates the DEPOTPCAREA table where the nominal code must be looked up from:
CREATE TABLE #DEPOTPCAREA (PCDSECTOR nvarchar(6), NLCC varchar(8));
INSERT INTO #DEPOTPCAREA (PCDSECTOR, NLCC) VALUES ('SL9 0','17');
INSERT INTO #DEPOTPCAREA (PCDSECTOR, NLCC) VALUES ('SL6 1','14');
INSERT INTO #DEPOTPCAREA (PCDSECTOR, NLCC) VALUES ('SL6 5','14');
INSERT INTO #DEPOTPCAREA (PCDSECTOR, NLCC) VALUES ('SL6 2','14');
INSERT INTO #DEPOTPCAREA (PCDSECTOR, NLCC) VALUES ('SL0 9','17');
INSERT INTO #DEPOTPCAREA (PCDSECTOR, NLCC) VALUES ('SL5 7','14');
The code below on it's own gets me the postcode sector from a given postcode correctly, I just can't work out how to use it in the join to the DEPOTPCAREA table in order to look up and retrieve the NLCC:
DECLARE @postcode VARCHAR(20)
SET @postcode = 'SL9 0LY'
SELECT SUBSTRING(postcode, start, length - start - fromEnd) AS PCDSECTOR
FROM (
	SELECT MAX(PATINDEX([matched], @postcode)) AS start
		,MAX(PATINDEX([ReverseMatch], reverse(@postcode + ' '))) - 1 AS fromEnd
		,len(@postcode + '||') AS [length]
		,@postcode AS postcode
	FROM (
		SELECT '[A-Z][A-Z0-9] [0-9]%'
			,'%[0-9] [A-Z0-9][A-Z]'
		
		UNION
		
		SELECT '[A-Z][A-Z0-9][A-Z0-9] [0-9]%'
			,'%[0-9] [A-Z0-9][A-Z0-9][A-Z]'
		
		UNION
		
		SELECT '[A-Z][A-Z0-9][A-Z0-9][A-Z0-9] [0-9]%'
			,'%[0-9] [A-Z0-9][A-Z0-9][A-Z0-9][A-Z]'
		) a(MATCHED, ReverseMatch)
	) pc
Result: SL9 0 = correct, but I need to use this to bring back the NLCC value of 17 from the DEPOTPCAREA table
Any help would be appreciated.
 
 
