How to find & replace ~ separated value

Sudip Bhatt 2,281 Reputation points
2020-12-03T13:24:17.56+00:00

say this is my text and multiple value is there separated by ~

SET @oldGroupKeyvalue='Consensus Model~Total Revenue~TRIN~NBM~~1~ZB-P1'

i want to pick value from 2nd ~ to 3rd ~ and replace by some other value.

How can i easily pick value from second tilde and to third tilde. so desire picked value will be TRIN

and want to replace TRIN with RD_101
please share the code to do it easy way. thanks

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


6 answers

Sort by: Oldest
  1. Yitzhak Khabinsky 27,196 Reputation points
    2020-12-08T04:21:34.207+00:00

    Here is another more simple version.

    SQL

    DECLARE @oldGroupKeyvalue  VARCHAR(MAX) = 'Consensus Model~Total Revenue~TRIN~NBM~~1~ZB-P1' 
        , @NewThirdToken VARCHAR(20) =  'NEW'
        , @separator CHAR(1) = '~';
    
     SELECT @oldGroupKeyvalue AS [Before]
     , REPLACE(
     TRY_CAST('<root><r>' + 
                 REPLACE(@oldGroupKeyvalue, @separator, '</r><r>') + 
                 '</r></root>' AS XML)
        .query('
        for $x in /root/r
        let $pos := count(/root/r[. << $x[1]]) + 1
        return 
        if ($pos = 3) then concat(sql:variable("@NewThirdToken"), sql:variable("@separator"))
        else 
            if ($x is (/root/r[last()])[1]) then data($x)
            else concat($x, sql:variable("@separator"))
     ')
    .value('.', 'NVARCHAR(MAX)')
    ,@separator + SPACE(1), @separator) AS [After];
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.