Pergunta

In one of the tables, there is a XML Data type column, which has several nodes and child data. I want to write SQL select statement which filters data from specific nodes from all rows and gives those rows which has specific values in the xml in the column.

If it is possible, I need the syntax of SQL select query and where condition. I am using SQL Server 2012.

Thanks.

Foi útil?

Solução

this is an example of select query to get a value in xml data

select 
    tt.id 
    ,cast(x.e.query('.') as nvarchar(50)) as [xml]
    ,x.e.value('(@ID)[1]','nvarchar(10)') as ID
    ,x.e.value('(@Name)[1]','nvarchar(10)') as Name
from @temp tt
cross apply tt.xxml.nodes('/FullData/Employees/Employee') as x(e)

/*
RESULT
id          xml                                                ID         Name
----------- -------------------------------------------------- ---------- ----------
1           <Employee ID="001" Name="David"/>                  001        David
1           <Employee ID="002" Name="Mike"/>                   002        Mike
1           <Employee ID="003" Name="Alex"/>                   003        Alex
1           <Employee ID="004" Name="Morris"/>                 004        Morris
2           <Employee ID="005" Name="Fox"/>                    005        Fox
2           <Employee ID="006" Name="Perry"/>                  006        Perry
2           <Employee ID="007" Name="Duals"/>                  007        Duals
2           <Employee ID="008" Name="Harry"/>                  008        Harry


*/ 

Note:

  1. the @temp table has 2 fields "Id" (int identity) and "xxml" (xml).
  2. the xml sample:

<FullData> <Employees> <Employee ID="005" Name="Fox" /> <Employee ID="006" Name="Perry" /> <Employee ID="007" Name="Duals" /> <Employee ID="008" Name="Harry" /> </Employees> <Departments> <Department ID="02" Name="Mobiles"/> </Departments> <Groups> <Group Name="Electronics" /> </Groups> </FullData>

  1. use @SOME_ATTRIBUTE to select attribute in a node x.e.value('(@ID)[1]','nvarchar(10)')

  2. to select a value from nodes x.e.value

    a.myXML.query('data(/Document/Controls/Control[1])').value('text()[1]','nvarchar(max)') as 'Vendor_Name'

UPDATED
with where clause

select 
    tt.id 
    --,cast(x.e.query('.') as nvarchar(max)) as [xml]
    ,x.e.value('(@ID)[1]','nvarchar(10)') as ID
    ,x.e.value('(@Name)[1]','nvarchar(10)') as Name --get /FullData/Employees/Employee attribute value
    ,x.e.value('.','nvarchar(20)') as email -- get /FullData/Employees/Employee node value
from @temp tt
cross apply tt.xxml.nodes('/FullData/Employees/Employee') as x(e)
where x.e.value('(@ID)[1]','nvarchar(10)') in( '001','002')

/*
RESULT

id          ID         Name       email
----------- ---------- ---------- --------------------
1           001        David      David@yahuu.com
1           002        Mike       Mike@yahuu.com
*/
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top