I have 2 stored procedures which return the same columns that I am trying to merge into a single procedure. They both have a different set of parameters and both have different WHERE clauses, but they use the same tables and select the exact same rows.
WHERE clause 1: (uses @UIOID, and @Level)
WHERE ( @UIOID = CASE WHEN @Level = 'Single' THEN C.C_UIOID_PK
WHEN @Level = 'Children' THEN CLC.UIOL_P
WHEN @Level = 'Parent' THEN CLP.UIOL_C
END
OR ( @UIOID = '0'
AND @Level = 'All'
)
)
Where clause 2: (Uses @TeamCode, @Year, @IncludeQCodes)
WHERE C.C_IsChild = 0
AND C.C_MOA <> 'ADD'
AND @TeamCode = C.C_OffOrg
AND C.C_Active = 'Y'
AND ( @Year BETWEEN dbo.f_GetAcYearByDate(C.C_StartDate) AND dbo.f_GetAcYearByDate(C.C_EndDate)
OR @Year = 0 )
AND ( C.C_InstCode NOT LIKE 'Q%'
OR @IncludeQCodes = 1 )
Ideally I want to add a new parameter which basically tells it which of the two WHERE clauses to run, but I can't seem to recreate that with CASE statement because as far as I can tell, they only work for a single WHERE clause, not a whole set of different clauses
I want to do this without having to repeat the select statement again and putting the whole thing in IF statements, and i don't want to put the query into a string either. I just want one select statement ideally.
The problem with using temp tables is the query itself takes a while to run without any parameters and is used in a live website, so I don't want it to have to put all records in a temp table and then filter it.
The problem with using a CTE is you can't follow it with an IF statement, so that wouldn't work either.
Here is the sort of logic I am trying to achieve:
SELECT A
B
C
FROM X
IF @WhichOption = 1 THEN
WHERE ( @UIOID = CASE WHEN @Level = 'Single' THEN C.C_UIOID_PK
WHEN @Level = 'Children' THEN CLC.UIOL_P
WHEN @Level = 'Parent' THEN CLP.UIOL_C
END
OR ( @UIOID = '0'
AND @Level = 'All'
)
)
ELSE IF @WhichOption = 2 THEN
WHERE C.C_IsChild = 0
AND C.C_MOA <> 'ADD'
AND @TeamCode = C.C_OffOrg
AND C.C_Active = 'Y'
AND ( @Year BETWEEN dbo.f_GetAcYearByDate(C.C_StartDate) AND dbo.f_GetAcYearByDate(C.C_EndDate)
OR @Year = 0 )
AND ( C.C_InstCode NOT LIKE 'Q%'
OR @IncludeQCodes = 1 )