I am listing a example code by which you can used COALESCE and CASE to create a store procedure that usually supports both dynamic WHERE and ORDER BY. There are many examples on the net also. If possible refer them also to get more information. Refer the below code.
Code:
CREATE PROCEDURE ps_Player_SELECT_ByStats (
@OrderBy tinyint = 1,
@Pla_BattingAverage smallint = NULL,
@Pla_HomeRuns smallint = NULL,
@Pla_RBIs smallint = NULL,
@Pla_StolenBases smallint = NULL,
@RowsReturned smallint = NULL OUTPUT )
AS
SET NOCOUNT ON
SELECT Pla_FName+' '+Pla_LName AS Name,
Pla_BattingAverage,
Pla_HomeRuns,
Pla_RBIs,
Pla_StolenBases
FROM Players
WHERE Pla_BattingAverage >= COALESCE(@Pla_BattingAverage,0) AND
Pla_HomeRuns >= COALESCE(@Pla_HomeRuns,0) AND
Pla_RBIs >= COALESCE(@Pla_RBIs,0) AND
Pla_StolenBases >= COALESCE(@Pla_StolenBases,0)
ORDER BY CASE WHEN @OrderBY = 1 THEN Pla_BattingAverage
WHEN @OrderBY = 2 THEN Pla_HomeRuns
WHEN @OrderBY = 3 THEN Pla_RBIs
WHEN @OrderBY = 4 THEN Pla_StolenBases
END DESC
SET @RowsReturned = @@ROWCOUNT
Bookmarks