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: Newest
  1. Yitzhak Khabinsky 27,196 Reputation points
    2020-12-03T13:35:07.593+00:00

    Same as before. XML data model is based on ORDERED sequences. That's why it is so easy to get to the 3rd token.

    SQL

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

    Was this answer helpful?

    1 person found this answer helpful.

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.