从没有CASE的列中按特定值排序

时间:2013-02-19 11:37:56

标签: sql-server sql-order-by

我有一个带有Id和名称的订单表

1  Fruits
33 Liquor
48 Tennis bats
58 Vegetables 
95 Poker cards

SELECT * FROM Order ORDER BY... Id = (48, 95, 33, 1, 58)

结果应该是

48 Tennis bats
95 Poker cards
33 Liquor
1  Fruits
58 Vegetables 

问:如何按照我想要的列的值订购此记录?

我想制作一个通用函数(可能是存储过程),所以我不能使用CASE方法:

CASE WHEN Id=48 THEN 0 ELSE 1  END, -- Not this way!!!!

1 个答案:

答案 0 :(得分:1)

create table [Order] (
  ID int, Name varchar(32)
)

insert into [Order]
  values (1, 'Fruits'),
         (33, 'Liquor'),
         (48, 'Tennis bats'),
         (58, 'Vegetables'),
         (95, 'Poker cards')
GO

create function dbo.Orderer(@id int, @orderString varchar(1024))
returns int
as
begin
  set @orderString = replace(',' + @orderString + ',', ' ', '');

  declare @pos int, 
          @str varchar(1024), 
          @itemOrder int;

  set @pos = charindex(',' + cast(@id as varchar(16)) + ',', @orderString);
  if @pos != 0
  begin
    set @orderString = substring(@orderString, 1, @pos + 1);
    set @pos = charindex(',', @orderString);
    set @itemOrder = 0;

    while @pos != 0
    begin
      set @itemOrder += 1;

      set @pos = charindex(',', @orderString, @pos + 1);
    end

    return @itemOrder
  end

  return null
end
GO

select * from [Order]
order by dbo.Orderer(ID, '48, 95, 33, 1, 58')