我编写了以下脚本来模拟来自数据表的传入参数并尝试使用参数过滤结果。一切正常,除了 order by 子句。基本上它只按行号排序,不考虑按列提供第二个顺序的 case 语句。
declare @sSortColumn as nvarchar(50)='Country';
declare @sSortDirection as nvarchar(5) = 'Desc';
declare @sSearch as nvarchar(50) = '';
declare @iDisplayLength as int = 20;
declare @iDisplayStart as int = 20;
declare @sIDsearch as int = CASE WHEN ISNUMERIC(@sSearch) = 1 THEN CAST(@sSearch AS INT) ELSE 0 END;
WITH media AS
(
select ROW_NUMBER() OVER (ORDER BY mc.id) as RowNumber,
mc.id,mc.Name, mc.CityID,lc.Name as Country
from Lookup_MediaChannels mc
left join Lookup_SonarMediaTypes st on mc.SonarMediaTypeID = st.ID
left join Lookup_SonarMediaGroups sg on sg.ID = st.SonarMediaGroupID
left join Lookup_MediaTypes mt on mc.MediaTypeID = mt.ID
left join Lookup_SonarMediaGroups sg1 on sg1.ID = mt.MediaGroupID
left join lookup_Countries lc on lc.id = mc.countryid
where mc.Name like '%'+@sSearch+'%'
and (sg1.ID=1 or sg.ID =1 )
or mc.id = @sIDsearch
)
SELECT RowNumber, Name, Country
FROM media
WHERE RowNumber BETWEEN (@iDisplayStart+ 1) AND (@iDisplayStart+ @iDisplayLength)
order by rownumber,
CASE WHEN @sSortColumn = 'Name' AND @sSortDirection = 'Desc'
THEN Name END DESC,
CASE WHEN @sSortColumn = 'Name' AND @sSortDirection != 'Desc'
THEN Name END,
CASE WHEN @sSortColumn = 'Country' AND @sSortDirection = 'Desc'
THEN Country END DESC,
CASE WHEN @sSortColumn = 'Country' AND @sSortDirection != 'Desc'
THEN Country END