简体   繁体   中英

How to extract values with a specific data from an XML column?

I have a query that gave an error that i dont know exactly why gave that error. What is the problem?

   SELECT top 10 [ID]
      ,[EVENTCLASS]
      ,[EVENTNAME]
      ,[EVENTDATA]
      ,[EVENTDATE]
      ,[BYUSER]
      ,[IDENTIFIER]
      ,[ZONE]
      ,[ARCHIVED]
      , metadata.value('(./@Value)[1]', 'nvarchar(max)') as CurrentEvent
FROM [dbo].[EventLog] with(nolock)
  cross apply eventdata.nodes ('/document/data[@name = ''EventStatus'']') as metadata
  where convert (date, eventdate) > '2019-04-15'
  and  metadata.value('(./@value)[1]', 'nvarchar(max)') = 'Recognized'

I have to search in Eventdata column that is an XML like this :

<Document ID="50f1c559-7a2a-4420-8fcb-de1e3d523c1a" Action="CREATE">
  <Data Name="EventTenant" Value="soc" Type="System.String" />
  <Data Name="TargetTenant" Value="soc" Type="System.String" />
  <Data Name="UserId" Value="519" Type="System.Int32" />
  <Data Name="EventStatus" Value="Recognized" Type="System.String" />
  <Data Name="TimeStamp" Value="2019-03-15 12:22:02.095" Type="System.String" />
  <Data Name="NextEventStatus" Value="Exported" Type="System.String" />
  <Data Name="NextEventAppId" Value="003" Type="System.String" />
  <Data Name="DocumentId" Value="50f1c559-7a2a-4420-8fcb-de1e3d523c1a,003" Type="System.String" />
</Document>

I want to search by EventStatus and its value.

You are shredding on nodes where Name=EventStatus and you use a where clause where Value=Recognized .

Those can be combined into one using exist something like this.

SELECT top 10 [ID]
      ,[EVENTCLASS]
      ,[EVENTNAME]
      ,[EVENTDATA]
      ,[EVENTDATE]
      ,[BYUSER]
      ,[IDENTIFIER]
      ,[ZONE]
      ,[ARCHIVED]
FROM [dbo].[EventLog]
where convert (date, eventdate) > '2019-04-15'
  and eventdata.exist('/Document/Data[@Name = "EventStatus" and @Value = "Recognized"]') = 1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM