TSQL从连接字符串中删除最后一个逗号

时间:2013-10-01 11:35:08

标签: sql sql-server tsql

我有一个带有连接值的列,但字符串最后带有一个逗号。 如何删除现有值的最后一个逗号?

SELECT 

    m.Mais_Id
    , m.Outro

    (SELECT CAST(emp.First_Name + ' ' + emp.Last_Name + ', ' AS VARCHAR(MAX)) 
    FROM 
        Patos p
    LEFT JOIN 
        Employee emp
    ON
        p.Pato_Id = emp.Pato_Id
        WHERE
        m.Pato_Id = p.Pato_Id
    FOR XML PATH ('')
    ) AS Names
FROM    
    Mais m

我有这个:

Mais_Id Outro Names
0       As    Adn Meas, Fjds Poi, Csa Drop,
1       Be    
2       Tee   As Been,

这是假装的结果:

Mais_Id Outro Names
0       As    Adn Meas, Fjds Poi, Csa Drop
1       Be    
2       Tee   As Been

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用stuff()函数:

stuff(
    (
        select ', ' + cast(emp.First_Name + ' ' + emp.Last_Name as varchar(max)) 
        from Patos as p
            left outer join Employee as emp on p.Pato_Id = emp.Pato_Id
        where m.Pato_Id = p.Pato_Id
        for xml path(''), type
    ).value('.', 'nvarchar(max)')
, 1, 2, '')  as Names

请注意,使用value()函数获取连接字符串也更安全,因此如果您有特殊字符,例如&或者<它将被正确显示。

答案 1 :(得分:0)

试试这个:

SELECT Mais_id, m.Outro, Substring(newColumn, 0, LEN(newColumn) - 1)
FROM (

SELECT 

    m.Mais_Id
    , m.Outro

    (SELECT CAST(emp.First_Name + ' ' + emp.Last_Name + ', ' AS VARCHAR(MAX)) as newColumn
    FROM 
        Patos p
    LEFT JOIN 
        Employee emp
    ON
        p.Pato_Id = emp.Pato_Id
        WHERE
        m.Pato_Id = p.Pato_Id
    FOR XML PATH ('')
    ) AS Names
FROM    
    Mais m
)