SQL:删除字符串中的最后一个逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31420597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL : remove last comma in string
提问by Justin
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.
我在 SQL 表中有一个文本备注字段,如果它是逗号,我需要删除该字段中的最后一个字符。
So, for example, if I have these rows, I need to remove the commas from rows 2 and 4.
因此,例如,如果我有这些行,我需要从第 2 行和第 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?
有任何想法吗?
回答by Sachu
Use case statement if the particular string is ending with , take the substring with LEFT function and lenght - 1
如果特定字符串以 结尾,则使用 case 语句,使用 LEFT 函数和 lenght - 1 取子字符串
Select
CASE
WHEN INETSHORTD LIKE '%,' THEN LEFT(INETSHORTD, LEN(INETSHORTD)-1)
ELSE INETSHORTD
END
From yourtable
回答by Felix Pamittan
Using REVERSE
and STUFF
:
使用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
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, '')
.
首先,您希望TRIM
您的数据摆脱前导和尾随空格。然后REVERSE
它并检查第一个字符是否为,
. 如果是,删除它,否则什么都不做。然后REVERSE
它又回来了。您可以使用 删除第一个字符STUFF(string, 1, 1, '')
。
回答by Drew Leffelman
Using CHARINDEX (https://msdn.microsoft.com/en-us/library/ms186323.aspx) AND LEN (https://msdn.microsoft.com/en-us/library/ms190329.aspx) you should be able to do it like this:
使用 CHARINDEX ( https://msdn.microsoft.com/en-us/library/ms186323.aspx) 和 LEN ( https://msdn.microsoft.com/en-us/library/ms190329.aspx) 你应该能够这样做:
SELECT IIF( CHARINDEX( ',', tmp.SHORTD, LEN( tmp.SHORTD ) ) > 0
, LEFT( tmp.SHORTD, LEN( tmp.SHORTD ) - 1 )
, tmp.SHORTD )
FROM tmp
This SQL Fiddle shows it at work: http://sqlfiddle.com/#!3/a99c8/7.
这个 SQL Fiddle 在工作中展示了它:http://sqlfiddle.com/#!3/a99c8/7 。
回答by Yair Maron
Here's a more elegant / readable way:
这是一种更优雅/可读的方式:
SET @string = REPLACE(@string + '<END>', ',<END>', '')
if you can't be sure if last comma appear in string, use this:
如果您不能确定最后一个逗号是否出现在字符串中,请使用以下命令:
SET @string = REPLACE(REPLACE(@string + '<END>', ',<END>', ''), '<END>', '')
回答by mohan111
declare @t table (id varchar(20))
insert into @t(id)values ('94,'),('85,'),('94, 92'),('89, 99, 32,')
SELECT REVERSE(SUBSTRING( REVERSE(id), PATINDEX('%[A-Za-z0-9]%',REVERSE(id)),
LEN(id) - (PATINDEX('%[A-Za-z0-9]%',REVERSE(id)) - 1) ) )
FROM @t