A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
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];