0

我有一个带有 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!!!!
4

1 回答 1

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')
于 2013-02-19T19:39:43.067 回答