Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

sql server - SQL : remove last comma in string

I have a text memo field in SQL table that I need to remove the last character in the field if it's a comma.

So, for example, if I have these rows, I need to remove the commas from rows 2 and 4.

  INETSHORTD
1  94
2  85,
3  94, 92
4  89, 99, 32,

The output would be:

  INETSHORTD
  94
  85
  94, 92
  89, 99, 32

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using REVERSE and STUFF:

SELECT
    REVERSE(
        STUFF(
            REVERSE(LTRIM(RTRIM(INETSHORTD))), 
            1, 
            CASE WHEN SUBSTRING((REVERSE(LTRIM(RTRIM(INETSHORTD)))), 1, 1) = ',' THEN 1 ELSE 0 END, 
            ''
        )
    )
FROM tbl

First, you want to TRIM your data to get rid of leading and trailing spaces. Then REVERSE it and check if the first character is ,. If it is, remove it, otherwise do nothing. Then REVERSE it back again. You can remove the first character by using STUFF(string, 1, 1, '').

SQL Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...