Please try the following solution based on the PARSENAME()
function use.
A minimal reproducible example is not provided.
An assumption is made that the tokens column has just a single space character between words/tokens.
SQL #1
-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, tokens VARCHAR(256));
INSERT @tbl (tokens) VALUES
('INV PNI S000060803 1'),
('INV PNI P000035365 132'),
('INV PRVC S000059468 4'),
('INV PIV P000034785 2'),
('INV PIV T000034785 27');
-- DDL and sample data population, end
SELECT t.*
, PARSENAME(c, 2) AS result
FROM @tbl AS t
CROSS APPLY (SELECT REPLACE(tokens, SPACE(1), '.')) AS t1(c);
SQL #2
Implementation when there are multiple spaces between words/tokens.
SELECT t.*
, PARSENAME(c, 2) AS result
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<r><![CDATA[' + tokens + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)')) AS t1(x)
CROSS APPLY (SELECT REPLACE(x, SPACE(1), '.')) AS t2(c);
Output
id |
tokens |
result |
1 |
INV PNI S000060803 1 |
S000060803 |
2 |
INV PNI P000035365 132 |
P000035365 |
3 |
INV PRVC S000059468 4 |
S000059468 |
4 |
INV PIV P000034785 2 |
P000034785 |
5 |
INV PIV T000034785 27 |
T000034785 |