我如何 select 来自 table 的记录并按逗号分隔字符串中的 ID 对其排序?

How do I select records from a table and order it by ID in a comma separated string?

我正在使用 Microsoft SQL 服务器。

假设我有一个 table,其中包含以下字段:

ID, NAME
=========
1, John
2, Peter
3, Jenny
4, Robert
5, Alan

而且,我有一个逗号分隔的字符串,其中包含上面 table 中的 ID。假设字符串具有以下值:

Sort_order = "3,5,4,1,2"

如何从 table select 记录并按 Sort_order 排序?

select 的结果集应按以下顺序给出记录:

3, Jenny
5, Alan
4, Robert
1, John
2, Peter

你可以试试这个脚本-

DEMO HERE

--Consider this first parameter is you retrieved 
--order string from another table
DECLARE @order_ VARCHAR(MAX) = '3,5,4,1,2'

--Added Comma at the start and end of the order string
--So that id 1 and 11 do not conflict
DECLARE @order_new VARCHAR(MAX) = ','+@order_+','

SELECT *
FROM your_table
ORDER BY CHARINDEX(
    ','+CAST(id AS VARCHAR)+',
    ',@order_new,
    0
) 

您也可以忽略向订单字符串添加额外 逗号 的第二步,直接在脚本中执行,如下所示,这将 return 相同的输出-

SELECT *
FROM your_table
ORDER BY CHARINDEX(
    ','+CAST(id AS VARCHAR)+',',
    ','+@order_+',',
    0
)

这是最终输出-