Monday, January 14, 2019

SQL Column DRY - Here's how to reuse a heavily modified field without repeating the modification multiple times.

--Using the values clause you can later reference a column that has been modified in the query.

SELECT
(SELECT
SUBSTRING(DIGITS2, 1, 3) + '-' + SUBSTRING(DIGITS2, 4, 3) + '-' + SUBSTRING(DIGITS2, 7, 99) +
CASE
WHEN DIGITS2 LIKE '1%' THEN NULL
WHEN LEN(B.DIGITS2) < 10 THEN NUll --Originally used to remove extra long numbers but removes extension numbers so can't use. --WHEN LEN(DIGITS2) > 10 THEN null
ELSE ''
END
FROM (VALUES((SELECT
RIGHT(DIGITS, CASE
WHEN DIGITS LIKE '1%' THEN 10
ELSE 99
END)
FROM (VALUES(LEFT(REPLACE(TRANSLATE(PHONENUMBER, 'abcdefghijklmnopqrstuvwxyz+()- ,#+.&;_!:', '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'), '@', ''), 11))) AS A (DIGITS)))) AS B (DIGITS2))
AS PHONE_FIX
, *

FROM [YOURDB].DBO.[CUSTOMERS] a

No comments:

Post a Comment