I have a table column as nvarchar(max)containing the following XML data:
<?xml version="1.0" encoding="utf-8"?>
<SerializableAlertDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="SerializableContextAlertDetail">
<ContextName>Evénements PTI mobile</ContextName>
<EnumValueName>Pré Alerte immobilisme</EnumValueName>
</SerializableAlertDetail>
I would like to SELECT the concatenation of the 'ContextName' and 'EnumValueName' XML elements.
At first I simply tried to return one element, which works fine:
SELECT CAST(REPLACE(dbo.AlertDetail.Context, 'encoding="utf-8"', '') AS XML).value('(/SerializableAlertDetail/*[local-name() = "ContextName"])[1]', 'nvarchar(max)') As DisplayName FROM Table
Because I do not want to cast twice in the query, I'm looking for a way to destructure the XML column into a table and select columns from here. So far I'm stuck with the following invalid query:
SELECT T0.XML.value('ContextName', 'nvarchar(max)')
FROM Table c
CROSS APPLY (SELECT CAST(REPLACE(c.Context, 'encoding="utf-8"', '') AS XML)) as T(X)
CROSS APPLY T.X.nodes('SerializableAlertDetail') AS T0(XML)
But it fails with the following error message:
XQuery [T.X.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'
Any help appreciated.
EDIT 1
I've come to the following query that works but may probably not be optimal:
SELECT T0.XML.query('./ContextName').value('.', 'nvarchar(max)') + T0.XML.query('./EnumValueName').value('.', 'nvarchar(max)')
FROM Table c
CROSS APPLY (SELECT CAST(REPLACE(c.Context, 'encoding="utf-8"', '') AS XML)) as T(X)
CROSS APPLY T.X.nodes('SerializableAlertDetail') AS T0(XML)
EDIT 2
Replaced ntext by nvarchar(max) ;)