How can I add a character into a specified position into string in SQL SERVER?

前端 未结 9 2348
傲寒
傲寒 2021-02-19 07:48

I have a varchar field like:

195500
122222200

I need to change these values to:

1955.00
1222222.00
9条回答
  •  终归单人心
    2021-02-19 08:18

    Ran into something similar and came up with this, could probably change this to a function/SP to make it reusable. Scenario faced was inserting a specified character at different positions within the string, for a certain number of times.

    /*
     --- passed in string or column,  N'C4CB6B22250B'
     --- desired output, C4:CB:6B:22:25:0D
     --- Test values 
     --- declare @strToChange varchar(50) = N'C4:CB:6B:22:25:0B'
     --- declare @strToChange varchar(50) = N'C4CB6B22250B'
    */
    
    
    declare @strToChange varchar(50) = N'C4CB6B22250B'
    IF(SELECT LEN(@strToChange) - LEN(REPLACE(@strToChange, ':', ''))) > 0
        BEGIN
            ---returns count of specified char
            SELECT LEN(@strToChange) - LEN(REPLACE(@strToChange, ':', ''))
        END
            ELSE
        BEGIN
            declare @charCount int = 5; --# of times to insert the char
            declare @shiftPosition int = 2; -- inital insertion shift
            While(@charCount > 0)
                begin
                SET @strToChange = LEFT(@strToChange,len(@strToChange)- @shiftPosition) + ':' + RIGHT(@strToChange,@shiftPosition)
                SET @charCount = @charCount - 1 --decrement charCount for each added char
                SET @shiftPosition = @shiftPosition + 3 ---increment shift position by 3 for the new char and the chars that were already there
            end
        SELECT @strToChange
    END
    

提交回复
热议问题