SQL从连锁列中删除最后一个逗号

时间:2017-04-13 11:03:07

标签: sql sql-server

我正在尝试通过添加逗号来连接我正在分隔的列。我想删除最后一个逗号,我能想到的唯一方法就是使用下面这个错综复杂的方法:

SELECT        
id,

CASE WHEN LEN(
            ISNULL(CASE WHEN intExtraTime > 0 THEN Convert(varchar(3),intExtraTime) + '% Extra Time, ' END,'') + 
            ISNULL(CASE WHEN intprocessor = 1 THEN 'Laptop, ' END,'') +
            ISNULL(CASE WHEN intRest = 1 THEN 'Rest Break, ' END,'') + 
            ISNULL(CASE WHEN intReader = 1 THEN 'Reader, ' END,'') +
            ISNULL(CASE WHEN intScribe = 1 THEN 'Scribe, ' END,''))>0 
THEN 
    SUBSTRING(
                ISNULL(CASE WHEN intExtraTime > 0 THEN Convert(varchar(3),intExtraTime) + '% Extra Time, ' END,'') + 
                ISNULL(CASE WHEN intprocessor = 1 THEN 'Laptop, ' END,'') +
                ISNULL(CASE WHEN intRest = 1 THEN 'Rest Break, ' END,'') + 
                ISNULL(CASE WHEN intReader = 1 THEN 'Reader, ' END,'') +
                ISNULL(CASE WHEN intScribe = 1 THEN 'Scribe, ' END,''),1,
            LEN(
                ISNULL(CASE WHEN intExtraTime > 0 THEN Convert(varchar(3),intExtraTime) + '% Extra Time, ' END,'') + 
                ISNULL(CASE WHEN intprocessor = 1 THEN 'Laptop, ' END,'') +
                ISNULL(CASE WHEN intRest = 1 THEN 'Rest Break, ' END,'') + 
                ISNULL(CASE WHEN intReader = 1 THEN 'Reader, ' END,'') +
                ISNULL(CASE WHEN intScribe = 1 THEN 'Scribe, ' END,''))-1)
END

FROM            dbo.Candidate AS ExamOptions 

任何人都知道更清洁的方法吗?

1 个答案:

答案 0 :(得分:1)

我假设你正在使用SQL Server,基于语法。

我不会通过删除 last 逗号来执行此操作。我会通过使用stuff()删除第一个逗号来完成此操作:

SELECT (CASE WHEN intExtraTime > 0 or intprocessor = 1 or intRest = 1 or
                 intReader = 1 or intScribe = 1
             THEN STUFF(COALESCE(CASE WHEN intExtraTime > 0 THEN ', ' + Convert(varchar(3), intExtraTime) + '% Extra Time' END,  '')
                        COALESCE(CASE WHEN intprocessor = 1 THEN ', Laptop' END, '') +
                        COALESCE(CASE WHEN intRest = 1 THEN ', Rest Break' END, '') + 
                        COALESCE(CASE WHEN intReader = 1 THEN ', Reader' END, '') +
                        COALESCE(CASE WHEN intScribe = 1 THEN ', Scribe' END, ''),
                        1, 2, '')
       END)
FROM dbo.Candidate ExamOptions;