我想创建一个存储过程来获取分页排序结果,但这是扭曲。我必须添加一列并用计算/计算数据填充它。目前我有
ALTER proc [dbo].[pr_GetPagedSortedOrdersByUser]
(
@userid numeric(18,0),
@CurrentPage int,
@PageSize int,
@SortField varchar(200),
@SortOrder varchar(5),
@status varchar(50)
)
as
begin
with temp as
(
select *
,ROW_NUMBER() OVER (order by
CASE WHEN @SortField = 'orderdate' AND @SortOrder = 'Desc' THEN orderdate END DESC,
CASE WHEN @SortField = 'orderdate' THEN orderdate END,
CASE WHEN @SortField = 'netamount' AND @SortOrder = 'Desc' THEN netamount END DESC,
CASE WHEN @SortField = 'netamount' THEN netamount END,
CASE WHEN @SortField = 'id' AND @SortOrder = 'Desc' THEN id END DESC,
CASE WHEN @SortField = 'id' THEN id END
) AS ROWID
from tbOrder
where (@status='All' or delivered=@status)and userid=@userid
)
select * ,
(
netamount - discount
) as 'Gross'
from temp
where rowid>((@CurrentPage - 1) * @PageSize) and rowid <(@CurrentPage * @PageSize + 1)
select count(*) as [count]
from tbOrder
where (delivered=@status or @status='All')and userid=@userid
end
注意:数据库中不存在 Gross
列,我应该能够将值Gross
传递给@SortField
答案 0 :(得分:0)
您应该只需将计算列添加到case语句中即可按其排序:
select *
,ROW_NUMBER() OVER (order by
CASE WHEN @SortField = 'orderdate' AND @SortOrder = 'Desc' THEN orderdate END DESC,
CASE WHEN @SortField = 'orderdate' THEN orderdate END,
CASE WHEN @SortField = 'netamount' AND @SortOrder = 'Desc' THEN netamount END DESC,
CASE WHEN @SortField = 'netamount' THEN netamount END,
CASE WHEN @SortField = 'id' AND @SortOrder = 'Desc' THEN id END DESC,
CASE WHEN @SortField = 'id' THEN id END,
CASE WHEN @SortField = 'gross' AND @SortOrder = 'Desc' THEN netamount - discount END DESC,
CASE WHEN @SortField = 'gross' THEN netamount - discount END
) AS ROWID
from tbOrder