开发者

SQL, remove appearances of a comma at end of the comma seperated list

How can we remove last comma from a comma seperated list in SQL query?

I have done a sample where i get a comma seperated string as output. But i found that a comma is comming after the string开发者_开发技巧 ends. I have tried to trim it of but was not able to do it.Can any one help me in getting it off?

my resulting string looks like this

eg:- some text, some more text, even more, yet more,


DECLARE @my_string nvarchar(128)
SET @my_string = N'Some Text, Some More Text, Even More, Yet More,'

select SUBSTRING(@my_string, 1, LEN(@my_string) - 1)

Should you need further assistance, you should provide further information.


Update MyTable
Set MyField = Case
                When Right(MyField,1) = ',' Then Substring( MyField, 1, Len(MyField) - 1 )
                Else MyField
                End

Btw, another alternative:

Update MyTable
Set MyField =  Substring( MyField, 1, Len(MyField) - 1 )
Where Value Like '%,'

Test script:

Declare @TestValues Table ( Value nvarchar(100) not null )

Insert @TestValues(Value) Values( 'XYZZY' )
Insert @TestValues(Value) Values( 'PLUGH' )
Insert @TestValues(Value) Values( 'SpiffyValueWithComma,' )

Select Case
        When Right(Value,1) = ',' Then Substring( Value, 1, Len(Value) - 1 )
        Else Value
        End
From @TestValues

Results:

XYZZY
PLUGH
SpiffyValueWithComma

Update

One possibiity is that your trailing value isn't a comma but rather a comma and a space. If that's the case, then you need to modify your query like so:

Update MyTable
Set MyField = Substring( MyField, 1, Len(MyField) - 1 )
Where Value Like '%,'
    Or Value Like '%, '
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜