数据
Approval_ID
-----------
1
2
3
4
5
6
7
8
9
10
查询
DECLARE
@id varchar(8000)
SELECT @id = COALESCE(@id + ', ', '') + '[' + Approval_ID + ']'
FROM (
SELECT DISTINCT Approval_ID
FROM Gate_III_CS_Approval
) Y
总是结果
1,10,2,3,4,5,6,7,8,9
我尝试添加“订购者”
ORDER BY len(Approval_ID), Approval_ID
但有错误
ORDER BY子句在派生的视图,内联函数中无效 表,子查询和公用表表达式,除非TOP,OFFSET 或还指定了FOR XML。
我想要这样的结果
1,2,3,4,5,6,7,8,9,10
我该怎么办?
更新:
;with cte as (
SELECT DISTINCT Approval_ID
FROM Gate_III_CS_Approval
)
SELECT @id = STUFF(
(SELECT concat(',', '[' + Approval_ID + ']')
FROM cte ORDER BY len(Approval_ID), Approval_id
FOR XML PATH('')
), 1, 1, '')
答案 0 :(得分:2)
使用CTE
和STUFF for XML PATH
-- replace CTE with your table, this is only an example
declare @id varchar(8000)
;with cte as (
select 1 n
union all
select n+1 n from
cte
where n < 10
)
select @id =
STUFF((
SELECT concat(',', n)
FROM cte
order by n
FOR XML PATH('')
), 1, 1, '')
select @id
programmatically cast n from alphanumeric to int for sorting
答案 1 :(得分:1)
为此,也许您可以尝试将varchar
转换为int
。我建立了一个示例here
DECLARE
@id varchar(8000)
SELECT @id = COALESCE(@id + ', ', '') + '[' + CAST(ID AS VARCHAR(10)) + ']'
FROM (
SELECT DISTINCT CAST(id AS INT) ID
FROM TABLA
) Y
SELECT @ID
答案 2 :(得分:1)
似乎您使用的是varchar字段,而不是Approval_ID的整数。
要根据varchar字段进行订购,可以尝试使用maSTAShuFu的答案中的方法。
在这里,我将使用问题中的查询进行更新。
SELECT STUFF(
(SELECT CONCAT(',[', Approval_ID,']')
FROM <your_table>
ORDER BY cast(Approval_ID as int)
FOR XML PATH('')), 1, 1, '')