I am trying to make a stored procedure and pass some parameters for filtering. As soon as filtering is in horizon, code has to be as generic as possible with as few as possible if, else, etc.
How could I make this more readable? Can I use functions for this?
ALTER PROCEDURE [dbo].[Stats] @network VARCHAR(9) = NULL,
@name VARCHAR(100) = NULL,
@version VARCHAR(15) = NULL,
@year INT = NULL,
@month INT = NULL,
@day INT = NULL,
@from DATE = null,
@to DATE = null
AS
BEGIN
SET nocount ON;
DECLARE @fromYear INT = NULL;
SET @fromYear = CASE WHEN @from IS NOT NULL THEN Datepart(year, @from) END
DECLARE @fromMonth INT = NULL;
SET @fromMonth = CASE WHEN @from IS NOT NULL THEN Datepart(month, @from) END
DECLARE @fromDay INT = NULL;
SET @fromDay = CASE WHEN @from IS NOT NULL THEN Datepart(day, @from) END
DECLARE @toYear INT = NULL;
SET @toYear = CASE WHEN @to IS NOT NULL THEN Datepart(year, @to) ELSE @fromYear END
DECLARE @toMonth INT = NULL;
SET @toMonth = CASE WHEN @to IS NOT NULL THEN Datepart(month, @to) ELSE @fromMonth END
DECLARE @toDay INT = NULL;
SET @toDay = CASE WHEN @to IS NOT NULL THEN Datepart(day, @to) ELSE @fromDay END
SELECT GS.[contractaddress],
GS.[network],
GS.[rounds],
GS.[sessions],
GS.[handle],
GS.[hold],
GS.[year],
GS.[month],
GS.[day],
G.[name],
G.[version],
DATEFROMPARTS(GS.[Year], GS.[Month], GS.[Day]) as [Date]
FROM [dbo].[gamestatsdaily] AS GS
INNER JOIN [dbo].[game] AS G
ON GS.contractaddress = G.[contractaddress]
WHERE ( @network IS NULL
OR ( GS.network = Upper(@network) ) )
AND ( @name IS NULL
OR ( GS.[contractaddress] IN (SELECT [contractaddress]
FROM [dbo].[game]
WHERE [name] = @name
AND [version] =
@version
AND [network] =
@network)
) )
AND ( @year IS NULL OR GS.[Year] = @year )
AND ( @month IS NULL OR GS.[Month] = @month )
AND ( @day IS NULL OR GS.[Day] = @day )
AND ( @from IS NULL OR ( GS.[Year] <= @fromYear AND @toYear >= GS.[Year] AND GS.[Month] <= @fromMonth AND @toMonth >= GS.[Month] AND GS.[Day] <= @fromMonth AND @toMonth >= GS.[Day]))
ORDER BY GS.[year] ASC,
GS.[month] ASC,
GS.[day] ASC
END

