Please try the following solution.
It is using XML/XQuery. Their data model is based on ordered sequences. Exactly what we need.
CROSS APPLY
converts Description column into XML data type.
- To get the last token, we are using the following XPath predicate:
/root/r[last()]
- To sort colors, we are using FLWOR expression with the
order by data($x) descending
clause.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, [Description] VARCHAR(255));
INSERT INTO @tbl ([Description]) VALUES
('Blue Black Red'),
('Cyan Green White');
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
-- without sorting
SELECT t.*
, c.value('(/root/r[last()]/text())[1]', 'VARCHAR(20)') AS lastColor
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
REPLACE([Description], @separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)) AS tab(c);
-- with sorting
SELECT t.*
, c.value('(/root/r[last()]/text())[1]', 'VARCHAR(20)') AS lastColor
, c
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
REPLACE([Description], @separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML).query('<root>
{
for $x in /root/r
order by data($x) descending
return $x
}
</root>
')) AS tab(c);
Output without sorting
+----+------------------+-----------+
| ID | Description | lastColor |
+----+------------------+-----------+
| 1 | Blue Black Red | Red |
| 2 | Cyan Green White | White |
+----+------------------+-----------+
Output with sorting
+----+------------------+-----------+
| ID | Description | lastColor |
+----+------------------+-----------+
| 1 | Blue Black Red | Black |
| 2 | Cyan Green White | Cyan |
+----+------------------+-----------+