SQL:删除字符串中的最后一个逗号
问题描述:
我在 SQL 表中有一个文本备注字段,如果它是逗号,我需要删除该字段中的最后一个字符.
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.
例如,如果我有这些行,我需要从第 2 行和第 4 行中删除逗号.
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,
输出将是:
INETSHORTD
94
85
94, 92
89, 99, 32
有什么想法吗?
答
使用REVERSE
和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
首先,您要TRIM
去除前导和尾随空格.然后REVERSE
,检查第一个字符是否为,
.如果是,删除它,否则什么都不做.然后 REVERSE
再次返回.您可以使用 STUFF(string, 1, 1, '')
删除第一个字符.
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, '')
.