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