删除尾随逗号sql

时间:2017-11-06 13:23:05

标签: sql sql-server

我知道这已被发布了一百万次,但我无法弄清楚如何在此示例中删除trailiing逗号。我不想创建一个新列,我只想浏览每一列,解析逗号分隔符列表并打印出这些代码及其描述。

例如,如果列表是GLU,那么我希望它打印: 不含麸质,素食。但是,我知道“面筋免费,素食主义者”,注意到最后的逗号。

以下是我目前的情况:

SELECT *,
    CASE WHEN( RE.FOODOPTIONS LIKE '%GLU%') THEN 'Gluten free,'
                  WHEN( RE.FOODOPTIONS LIKE '%ALL%') THEN 'Food Allergies,'
                  WHEN( RE.FOODOPTIONS LIKE '%VEG%') THEN 'Vegetarian,'
                  WHEN( RE.FOODOPTIONS LIKE '%OTHER%') THEN 'Other,'
    END
FROM RegExt AS RE 

感谢。

示例数据:

FOODOPTIONS: GLU, ALL, VEG 
Results: Gluten free, Food Allergies, Vegetarian,
Desired Results: Gluten free, Food Allergies, Vegetarian

FOODOPTIONS: GLU
Results: Gluten free,
Desired Results: Gluten free

FOODOPTIONS: GLU, VEG 
Results: Gluten free, Vegetarian,
Desired Results: Gluten free, Vegetarian

FOODOPTIONS的值是由逗号分隔的代码列表。它能够列出它们,但最后包括逗号。

3 个答案:

答案 0 :(得分:3)

你可以使用IIF,连接最后一个字符的字符串和印章

SELECT *,
reverse(stuff(reverse(
    IIF(FOODOPTIONS LIKE '%GLU%', 'Gluten free,', '')+
    IIF(FOODOPTIONS LIKE '%ALL%', 'Food Allergies,', '')+
    IIF(FOODOPTIONS LIKE '%VEG%', 'Vegetarian,', '')+
    IIF(FOODOPTIONS LIKE '%OTHER%', 'Other,', '')
), 1, 1, ''))
FROM RegExt;

由于你不知道字符串的长度,你可以反转字符串,切掉第一个字符并再次反转。

答案 1 :(得分:2)

我使用stuff()执行此操作:

SELECT re.*,
       STUFF( (CASE WHEN RE.FOODOPTIONS LIKE '%GLU%' THEN ',Gluten free' ELSE '' END) +
               CASE WHEN RE.FOODOPTIONS LIKE '%ALL%' THEN ',Food Allergies' ELSE '' END) +
               CASE WHEN RE.FOODOPTIONS LIKE '%VEG%' THEN ',Vegetarian'  ELSE '' END) +
               CASE WHEN RE.FOODOPTIONS LIKE '%OTHER%' THEN ',Other'  ELSE '' END
              ), 2, LENGTH(RE.FOODOPTIONS), ''
             )
FROM RegExt AS RE

答案 2 :(得分:0)

您可能会使用REPLACE三次?

DECLARE @FoodOptions varchar(100) = 'GLU, VEG'    
SELECT REPLACE( REPLACE( REPLACE (@FoodOptions, 'GLU', 'Gluten free'), 'ALL', 'Food Alergies'), 'VEG', 'Vegetarian') AS [ColumnName]

提供输出:

ColumnName
Gluten free, Vegetarian