How do I get --ALL-- to be at the top of my order by? I cannot use CASE WHEN in the ORDER BY clause because of the UNION. I also think the IF/ELSE is a complication here.
This code lives in an sp that I didn't write originally. I was asked to duplicate it and add a null value (the original script didn't have any nulls).
My solution was to UNION in
SELECT
NULL as parameterValue,
CAST('--All--' as VARCHAR(50)) AS parameterLabel
Now I need that Null, --All-- row to always be at the top of my results and the rest of the results to be parameterValue desc
I want to make this solution work, but I cannot figure out how to with the IF/Else: Order by a specific value first then show all rest in order
DECLARE
@MaxCampaignYear int,
@rptSection nvarchar(85) = 'Main',
@showAll bit = 0
SELECT
@MaxCampaignYear = MAX(campaignYearNum)
FROM
dbo.dimDate
IF @rptSection = 'Main'
SELECT
NULL as parameterValue,
CAST('--All--' as VARCHAR(50)) AS parameterLabel
UNION ALL
SELECT DISTINCT
campaignYearNum AS parameterValue,
CAST(campaignYearNum as VARCHAR(50)) AS parameterLabel
FROM
dbo.dimDate
WHERE
(
@showAll <> 0
or campaignYearNum <= @MaxCampaignYear --BI_DW.dbo.udfGetCampaignYear(getdate())
)
and campaignYearNum > 0
ORDER BY
parameterValue desc
ELSE
SELECT
BI_DW.dbo.udfGetCampaignYear(getdate()) as parameterValue,
BI_DW.dbo.udfGetCampaignYear(getdate()) as parameterLabel```