【问题标题】:SQL - Replace multiple different characters with a single character within a string?SQL - 用字符串中的单个字符替换多个不同的字符?
【发布时间】:2021-10-23 18:14:33
【问题描述】:

我想在 MS SQL 中清理字符串并用下划线_替换各种字符。

以下代码可以实现:

DECLARE @string nvarchar(MAX)
DECLARE @new_string nvarchar(MAX)
SET @string = 'This is.my string/That Needs=cleaning'

SET @new_string = REPLACE(REPLACE(REPLACE(REPLACE(@string, ' ', '_'), '.', '_'), '/', '_'), '=', '_')

SELECT @new_string

这将返回“This_is_my_string_That_Needs_cleaning”

我将使用它来清理文件名。

有没有更有效的方法,也许是通过正则表达式?

【问题讨论】:

    标签: sql sql-server replace


    【解决方案1】:

    SQL Server 2017+ 现在支持translate()

    select @new_string = translate(@string, ' ./=', '____')
    

    Here 是一个 dbfiddle。

    【讨论】:

    • 谢谢,这很有用。我目前正在使用 SQL Server 2014(即将升级,因此将保存此解决方案)。我认为这也意味着在 2017 年以下的版本中没有有效的方法(除了构建一个复制上述内容的函数)?
    • @Sharky99x 。 . .在旧版本中,嵌套的replaces() 可能是最好的解决方案。
    猜你喜欢
    • 2017-01-06
    • 2020-06-02
    • 2022-12-15
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多