【问题标题】:How to replace nth character in sql server如何替换sql server中的第n个字符
【发布时间】:2015-02-23 13:22:31
【问题描述】:

我正在尝试替换 SQL Server 中的第 n 个字符。我尝试使用replace()

SELECT REPLACE(ABC,0,1)  FROM XXX

在上面的代码中,所有的零都将被替换为一,但我只想在特定位置更改它,有时该位置可以更改。

【问题讨论】:

    标签: sql sql-server sql-server-2008


    【解决方案1】:

    使用东西 STUFF 函数将一个字符串插入另一个字符串。它在开始位置删除第一个字符串中指定长度的字符,然后将第二个字符串插入到开始位置的第一个字符串中。

    select STUFF(ABC, starting_index, 1, 'X') from XXX
    

    “Here your int position to replace”是位置 no 只需用任何 int no 替换,该位置将被替换 注意:(感谢pcnate 的建议) starting_index 是您要替换的 int 位置。

    【讨论】:

    • 我建议使用lenth_ofthestring_to_replace_from_starting_indexstarting_index 之类的假变量名来清楚地表明它应该是数字而不是字符串。用一个完整的句子来描述一个字符串只会使答案膨胀
    【解决方案2】:

    你正在寻找STUFF:

    select STUFF(ABC, @n, 1, 'X') from XXX
    

    这会将@nth 字符替换为X

    从技术上讲,它从@n 位置开始在ABC 列中查找原始字符串,删除1 字符,然后在该位置插入字符串'X'

    【讨论】:

      【解决方案3】:

      您为此使用STUFF

      SELECT STUFF(ABC, 5, 1, '1')
      FROM XXX
      

      这会将第 5 个字符替换为 1。

      【讨论】:

        【解决方案4】:

        使用stuff():

        select stuff(abc, 0, 1, 'a')
        

        记录在案here

        【讨论】:

        • 它也适用于变量:SET @MY_VARIABLE=STUFF(@MY_VARIABLE,14,1,'h');
        【解决方案5】:

        使用东西。

        STUFF(Column_Name,starting_index,
        lenth_ofthestring_to_replace_from_starting_index, character_to_replce)
        

        示例_

        DECLARE @str varchar(100) = '123456789'
        select @str
        SELECT STUFF(@str,2,1, 'hello') 
        -- want to replece 1 charter starting from 2nd position with the string 'hello'
        

        检查一下。

         SELECT STUFF(@str,2,25, 'hello'),len(@str)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-10-24
          • 2013-11-23
          • 1970-01-01
          • 2011-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多