I have a stored procedure to return the top 50 rows from a table, like this:
select top 50
Puzzle,
min(DateSolved) as CreationDate,
avg(SecondsToComplete) as AverageTime,
count(*) as TimesSolved
from CustomSolves
group by Puzzle
But I want the stored procedure to accept two parameters, so that I can order by a custom column (the creation date, the average time, or the times sovled) and only select records newer than a certain date. Something like this pseudo-SQL:
procedure SelectCustomPuzzles
@CutoffDate datetime,
@SortColumn column
as
select top 50
Puzzle,
min(DateSolved) as CreationDate,
avg(SecondsToComplete) as AverageTime,
count(*) as TimesSolved
from CustomSolves
where CreationDate > @CutOffDate
group by Puzzle
order by @SortColumn
How could I go about doing something like this?
Edit, for a default sort add one of these
Notes:
WHEN..THEN columnrequires datatypes to be implicitly CASTable. I prefer separate CASE expressions to avoid implicit conversions See https://dba.stackexchange.com/a/4166/630 for a worked example