【问题标题】:SQL Server, replace one or more consecutive charSQL Server,替换一个或多个连续字符
【发布时间】:2022-01-01 04:43:12
【问题描述】:

使用 SQL Server,是否可以替换一个或多个连续字符?

例如:

select replace(replace(replace('my string   to  split','  ',' '),'   ',' '),'    ',' ')

不使用循环?

【问题讨论】:

  • 如果它只是你想替换空格?还是有其他角色?
  • 无循环 - 什么循环在哪里?
  • @Luuk 如果你要推荐 Regex,你应该推荐一个 CLR 函数来使用所述 Regex。否则你的链接副本是没用的; SQL Server 不支持正则表达式。
  • @Larnu,在这种情况下,空格,但如果可能的话,一个通用的解决方案应该更好
  • @Stu,哇!好把戏!!

标签: sql sql-server split char trim


【解决方案1】:

无需循环

这是 Gordon Linoff 前段时间演示的一个小技巧。

  1. 展开
  2. 淘汰
  3. 恢复

您可以替换任何ODD 字符/字符串对组合,例如§§||

示例

Select replace(replace(replace('my string   to  split',' ','><'),'<>',''),'><',' ')

或更多唯一字符串

Select replace(replace(replace('my string   to  split',' ','§§||'),'||§§',''),'§§||',' ')

结果

my string to split

【讨论】:

    【解决方案2】:

    在循环结构中使用 charindex https://www.w3schools.com/sql/func_sqlserver_charindex.asp,然后使用变量来跟踪索引位置。

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 2016-06-23
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多