简体   繁体   English

SQL Server 2014:逗号后加空格

[英]SQL Server 2014: Add space after comma

I want to update only the values in Column1 that have characters of a string, then a comma, then (without a space) more characters, like so: abc,def or abc,123,def .我只想更新Column1中具有字符串字符的值,然后是逗号,然后(没有空格)更多字符,例如: abc,defabc,123,def I want a space to be added between the comma and the next character, like so: abc, def or abc, 123, def .我想在逗号和下一个字符之间添加一个空格,如下所示: abc, defabc, 123, def It shouldn't add an extra space if there already is one.如果已经有一个,它不应该添加一个额外的空间。

Sorry, I don't have any existing SQL to show-- I'm not sure where to even start on this.抱歉,我没有任何现有的 SQL 可以显示——我什至不确定从哪里开始。

I'd first replace all instances of , (comma + space) with , (comma, NO space). 我首先将, (逗号+空格)的所有实例替换为, (逗号,无空格)。 That way everything is uniform. 这样,一切都是统一的。 Then go the other way; 然后走另一条路; replace commas with comma + space 用逗号+空格替换逗号

Perhaps a little overkill, but this will support any combination of space(s) before and after a comma 也许有点矫kill过正,但这将支持逗号前后的任意空格组合

Example

Declare @S varchar(max) = 'abc  ,     123 , def,    ddd'

Select replace(replace(replace(replace(@S,',','<>'),' ','<>'),'><',''),'<>',', ')

Returns 退货

abc, 123, def, ddd

I should add , this is a little trick from Gordon several months ago. 我应该补充一点,这是几个月前戈登的一个小把戏。 I don't have the original link 我没有原始链接

I think you are need to first remove space and then add space to column1 near 我认为您需要先删除空间,然后向附近的column1添加空间

 UPDATE yt set yt.Column1 =replace(replace(yt.Column1 ,' ',''),',',', ')
  from yourtable yt
  where yt.Column1 like '%,%'

This would do what you are wanting 这会做你想要的

UPDATE TABLE
SET Col1 = REPLACE(REPLACE(Col1,', ',','),',',', ')
WHERE Col1 LIKE '%,%'

If one needs exactly one space after the comma and the data is not consistent there is also the option of a string_split and then string_agg:如果逗号后只需要一个空格并且数据不一致,则还可以选择 string_split,然后是 string_agg:

DECLARE @test varchar(max) = 'Test, Test 12,Test34,Test56 ,     Test78'
select STRING_AGG(Trim(value),', ') as Test from string_split(@test,',')

Result:结果:

Test, Test 12, Test34, Test56, Test78

If possible you should use the new "enable_ordinal" option of string_split, but i actually never had problems with the order.如果可能的话,你应该使用 string_split 的新“enable_ordinal”选项,但实际上我从来没有遇到过顺序问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM