【问题标题】:How to replace spaces with underscores in sub-strings within a long string in SQL server如何用下划线替换 SQL Server 中长字符串中的子字符串中的空格
【发布时间】:2022-01-03 12:26:00
【问题描述】:

使用 SQL Server 2019。

我有一个带有长字符串值的 VARCHAR(MAX) 列。这是字符串的一部分:

'`the night is dark` as A , `the day is shining` as B , `wind moves but breeze flows` as C '

Required output is:

'`the_night_is_dark` as A , `the_day_is_shining` as B , `wind_moves_but_breeze_flows` as C '

【问题讨论】:

    标签: sql sql-server replace varchar


    【解决方案1】:

    在 SQL Server 中,下面的函数可以解决问题。 (但如果我们有一个很长的字符串在子字符串中包含引号,这将不起作用)

    逻辑:我们找到字符的第一个位置,然后是它出现的第二个位置,并用'_'替换空格。将第一个位置更改为第二个位置并继续...

    CREATE OR ALTER FUNCTION replace_spc_with_uscore(@string VARCHAR(max)) RETURNS VARCHAR(max) as 
    BEGIN
    
    declare @max_cnt INT , @pos1 INT ,@pos2 INT = 1,@pos2_t INT = 1  , @tmp_str VARCHAR(max)=@string , @old_str VARCHAR(max) , @final_str VARCHAR(max)=@string
    
    select  @max_cnt= len(@string) - len(replace(@string, '`', '')) 
    
    while @max_cnt > 0 
        BEGIN
            select @pos1=CHARINDEX('`', @string , @pos2)
    
            select @pos2_t=CHARINDEX('`', @string , @pos1+1)
    
            select @pos2=CHARINDEX('`', @string , @pos1+1) - @pos1+1
    
            SELECT @old_str=SUBSTRING(@string,@pos1,@pos2) 
            SELECT @tmp_str=REPLACE (  SUBSTRING(@string,@pos1,@pos2)   ,' ','_')
    
            SELECT @final_str=REPLACE (@final_str, @old_str, @tmp_str)
            
            Select @max_cnt=@max_cnt-2  , @pos2=@pos2_t+1--@pos2+1
        END
        --select @final_str
    RETURN @final_str
    
    END
    

    希望在需要类似功能的情况下会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 2015-03-11
      • 1970-01-01
      • 2018-09-19
      • 2018-04-01
      • 1970-01-01
      相关资源
      最近更新 更多