- I find a function to split the string by space.
- Using REVERSE find out the last two words on each string.
- Checking
[last]
and [beforeLast]
:
- Can calculate how many chars remove from
[Addres1]
- Can determinate if
[last]
is Numeric then that mean [beforeLast]
will be [Address2]
other wise [last]
is [Address2]
- Can determinate if
[last]
is Numeric then I have a zip code.
SQL DEMO
WITH lastToken as (
SELECT [ID],
( SELECT REVERSE(s)
FROM dbo.SplitString(REVERSE(Address1), ' ')
WHERE zeroBasedOccurance = 0
) as last,
( SELECT REVERSE(s)
FROM dbo.SplitString(REVERSE(Address1), ' ')
WHERE zeroBasedOccurance = 1
) as beforeLast
FROM T1
)
SELECT T1.ID, T1.Name,
LEFT(T1.[Address1],
LEN([Address1]) -
CASE WHEN ISNUMERIC(last) = 1
THEN LEN(last) + LEN(beforeLast) + 2
ELSE LEN(last) + 1
END
) [Address1],
CASE WHEN ISNUMERIC(last) = 1
THEN beforeLast
ELSE last
END as [Address2],
CASE WHEN ISNUMERIC(last) = 1
THEN last
END as [zipcode],
T2.*
FROM T1
JOIN lastToken T2
ON T1.[ID] = T2.[ID];
OUTPUT
