How to cast varchar to XML in an OUTER APPLY query

2019-08-29 20:51发布

问题:

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?

回答1:

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)