在XML查询中用[text()]别名修剪逗号结尾

时间:2018-07-02 20:31:04

标签: sql-server tsql

我有以下sql,并且需要删去结尾的逗号(如果存在)。我是sql的业余爱好者,所以一点帮助/指导会很棒。

SELECT
    fse.FormSubmissionId,
    CASE
        WHEN fse.Type = 4
            THEN
                (SELECT fse2.FormElementItemText + ', ' as [text()] 
                 FROM dbo.FormSubmissionElement as fse2 
                 WHERE fse2.FormElementId = fse.FormElementId 
                 ORDER BY fse2.FormElementItemText DESC 
                 FOR XML PATH(''))
    END as UserSubmission

我环顾四周,发现了一些减少逗号结尾的方法,例如herehere。但是我不确定如何将其合并到当前的select语句中,因为[text()]的别名是XML

我敢肯定这很愚蠢,但是希望能得到您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以将其重写为:

SELECT
    fse.FormSubmissionId,
    CASE
       WHEN fse.Type = 4 THEN
       STUFF((SELECT ', ' + fse2.FormElementItemText as [text()]-- ', ' goes first
       FROM dbo.FormSubmissionElement as fse2 
       WHERE fse2.FormElementId = fse.FormElementId
       ORDER BY fse2.FormElementItemText DESC 
       FOR XML PATH('')
       ),1,2,'')    -- stuff will remove first 2 characters
END as UserSubmission
...

答案 1 :(得分:1)

如果您在逗号的开头而不是结尾添加逗号,则可以使用stuff删除它,如下所示:

SELECT
fse.FormSubmissionId,
CASE
    WHEN fse.Type = 4
        THEN
            STUFF((SELECT ', ' +fse2.FormElementItemText as [text()] 
                   FROM dbo.FormSubmissionElement as fse2 
                   WHERE fse2.FormElementId = fse.FormElementId 
                   ORDER BY fse2.FormElementItemText DESC 
                   FOR XML PATH('')), 1, 2, '')
END as UserSubmission

原因是您知道字符串始终从索引1开始,但是要知道最后一个索引是什么,您必须选择两次或使用变量。