0

我编写了以下脚本来模拟来自数据表的传入参数并尝试使用参数过滤结果。一切正常,除了 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
4

1 回答 1

1

这个简化的例子可以帮助你

http://sqlfiddle.com/#!6/35ffb/10

设置一些虚拟数据(这将被您的 select 语句替换)

create table x(
  id int,
  name varchar(3),
  country varchar(2)
)
insert into x 
values (1,'aaa','uk'),
(2,'aaa','us'),
(3,'baa','uk'),
(4,'caa','uk'),
(5,'baa','it')

一些变量来保存排序字段和排序顺序

declare @so char(1)
declare @sf char(1)
set @so = 'a' -- a = asc  d = desc
set @sf = 'n' -- n = name c = country

和一个返回排序数据的选择

  SELECT row_number() 
  OVER (order by 
          CASE WHEN @so =  'd' THEN sf END desc, 
          CASE WHEN @so <> 'd' THEN sf end,
          id
        ) AS aa, name,country
  FROM (
    SELECT x.*, case @sf when 'n' then name when 'c' then country end sf 
    FROM X
  ) X
于 2013-06-28T09:44:49.343 回答