Context
I was proud of this code for a little while, but the repetition wounds me. I know that the function name sucks, but the name and interface to this function are not under my control. Performance is not a concern.
Fixing the repetition is my only concern. How can I reduce it?
Note the usage of the functional-programming tag. If you suggest a multi-statement table-valued function, then you've failed me. This must be an inline table-valued function.
Dependencies
CREATE TABLE [WINNERS]
(
WINNER_ID INT NOT NULL
);
CREATE TABLE [RelevantWinners]
(
WINNER_ID INT NOT NULL
);
INSERT INTO [WINNERS]
VALUES (1), (2), (3), (4), (5);
INSERT INTO [RelevantWinners]
VALUES (1), (5);
The Code For Review
CREATE FUNCTION RecentWinners
(
@GetAllWinners BIT
)
RETURNS TABLE
AS
RETURN
(
-- Style note: I've yet to figure out how to best indent consecutive CTEs.
WITH
[WinnersRelevant] AS
(
SELECT
-- The inclusion of a silly calculation is deliberate.
2 * [Win].[WINNER_ID] + 47 [ENCODING]
FROM
[Winners] [Win]
WHERE EXISTS
(
SELECT 1
FROM [RelevantWinners] [Rev]
WHERE [Rev].[WINNER_ID] = [Win].[WINNER_ID]
)
),
[WinnersAll] AS
(
-- This is the first major repetition.
-- It's exactly the same code as before, but without the semi-join.
SELECT
2 * [Win].[WINNER_ID] + 47 [ENCODING]
FROM
[Winners] [Win]
)
SELECT
[ENCODING],
-- The inclusion of a second silly calculation is deliberate.
-- Pretend it's independent of the previous one.
2 * [ENCODING] + 12346 [ENCODING_2]
FROM
[WinnersRelevant]
WHERE
@GetAllWinners = 0
UNION ALL
-- This is the second major repetition.
-- It's exactly the same SELECT list as before.
SELECT
[ENCODING],
2 * [ENCODING] + 12346 [ENCODING_2]
FROM
[WinnersAll]
WHERE
@GetAllWinners = 1
); --I'm pretty sure this is the only relevant semicolon, even under strict standards.