Given the following sample SQL, it would work perfectly IF the two varchar(max)
declarations for both the XML itself and the @t table declaration were actually xml
field types.
DECLARE @x varchar(max) = '<?xml version="1.0" encoding="UTF-8"?>
<AuditTrail>
<Action />
<ActionDetail />
<ChangesXML>
<Details>
<Object ObjectType="Data.Review_Extension" AuditType="Modified" FriendlyName="Review">
<ObjectKeys>
<ReviewExtID>21482283</ReviewExtID>
</ObjectKeys>
<Properties>
<Property name="Document Type 01" FieldName="Document_Type_01" TemplateFieldID="644140" ReviewExtensionID="214822182" PropertyType="System.String">
<OldValue />
<NewValue><![CDATA[1145]]></NewValue>
</Property>
<Property name="Document Type 02" FieldName="Document_Type_02" TemplateFieldID="644141" ReviewExtensionID="21482283" PropertyType="System.String">
<OldValue />
<NewValue><![CDATA[123]]></NewValue>
</Property>
</Properties>
</Object>
</Details>
</ChangesXML>
</AuditTrail>'
DECLARE @t TABLE (userid INT, [xml] varchar(max))
INSERT @t VALUES(1, @x)
SELECT t.userid, r.z.value('@FieldName', 'nvarchar(MAX)')
FROM @t t
OUTER APPLY t.xml.nodes('//Property') as r(z)
How can I modify the SELECT query at the bottom of this SQL to cast the [xml] field to an XML field type so that I can use t.xml.nodes?
Just use one OUTER APPLY
first to force a CAST
:
SELECT t.userid, r.z.value('@FieldName', 'nvarchar(MAX)')
FROM @t t
OUTER APPLY (SELECT CAST(t.xml as xml) as realxml) s
OUTER APPLY s.realxml.nodes('//Property') as r(z)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.