I have a pretty long CASE WHEN
expression in a view which creates two dynamic columns given some logic.
However, now I need to add this same logic to another view and create the dynamic columns there. I could copy paste the same logic, but then any changes would have to be made in both places.
Is there an optimal way to centralize this logic and/or make it a function that the CREATE VIEW
statements can reference?
WITH_REPORTING_PIVOTS AS (
SELECT
I.*,
CASE
WHEN I.Code = 'Condition' THEN ISNULL(Type1, Type2)
WHEN Tag1 = 'Condition' THEN ISNULL(Tag2, Tag3)
WHEN I.Detail IS NOT NULL THEN
CONCAT(
CASE
WHEN
ISNULL(Code, Code2) IS NOT NULL
THEN
CONCAT(
ISNULL(Code, Code2),
' '
)
ELSE ''
END,
Detail
)
WHEN I.Type1 = 'Condition' THEN
CONCAT(
CASE
WHEN I.Code = 'Condition' THEN 'Value'
ELSE Code
END,
' ', I.Description,
' ', I.Type1
)
ELSE I.Tag1
END AS DyanmicColumn1,
CASE
WHEN
Tag1 = 'Condition'
THEN REPLACE(I.Tag4, 'string', '')
WHEN I.Code = 'Condition' THEN SubType
WHEN I.Detail IS NOT NULL THEN
CASE
WHEN ISNULL(SubTag, SubTag2) IS NOT NULL THEN
CASE
WHEN ISNULL(SubTag, SubTag2) = 'N/A' THEN NULL
ELSE ISNULL(SubTag, SubTag2)
END
END
ELSE Tag2
END AS DyanmicColumn2
4