[英]How do I select records from a table and order it by ID in a comma separated string?
我正在使用 Microsoft SQL Server。
假設我有一個表,其中包含以下字段:
ID, NAME
=========
1, John
2, Peter
3, Jenny
4, Robert
5, Alan
而且,我有一個逗號分隔的字符串,其中包含上表中的 ID。 假設字符串具有以下值:
Sort_order = "3,5,4,1,2"
如何從表中選擇記錄並按 Sort_order 排序?
選擇的結果集應按以下順序提供記錄:
3, Jenny
5, Alan
4, Robert
1, John
2, Peter
你可以試試這個腳本——
--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
)
您也可以忽略向訂單字符串添加額外逗號的第二步,直接在腳本中執行,如下所示,這將返回相同的輸出 -
SELECT *
FROM your_table
ORDER BY CHARINDEX(
','+CAST(id AS VARCHAR)+',',
','+@order_+',',
0
)
這是最終的輸出 -
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.