我有一个存储过程从表中返回前50行,像这样:如何通过参数为存储过程指定列?
select top 50
Puzzle,
min(DateSolved) as CreationDate,
avg(SecondsToComplete) as AverageTime,
count(*) as TimesSolved
from CustomSolves
group by Puzzle
但我想在存储过程接受两个参数,这样我可以通过自定义列顺序(创建日期,平均时间或时间),并且只选择比特定日期更新的记录。像这样的伪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
我怎么能去做这样的事情呢?
如何处理默认情况,以防排序列与任何情况不符? – 2011-12-17 18:28:08
@Peter Olson:更新了答案 – gbn 2011-12-17 18:35:40