简体   繁体   中英

Query xml using sql server

i am new to xml queries. i have one xml like

<fields>
<fields name = "a" active ="1" mandat ="true"/>
<fields name = "a" active ="1"/>
</fields>

Now i need to find all the field names that manadt is true. How can i query xml using sql server. please help

Your question is not quite clear, especially the tags ( sql, xml, c#-4.0 ), but from you question's text I take, that you need to query the XML's content within SQL-Server.

You can try it like this

DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="a" active="1" />
</fields>';

SELECT fld.value(N'@name',N'nvarchar(max)') AS Field_Name
      ,fld.value(N'@active',N'bit') AS Field_Active
      ,fld.value(N'@mandat',N'bit') AS Field_Mandant
FROM @xml.nodes(N'/fields/fields') AS A(fld)

The result

Field_Name  Field_Active    Field_Mandant
a           1               1
a           1               NULL

UPDATE

If you want to read the value of @name of the fields-node, where @mandat is "true" , do it like this:

DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="a" active="1" />
</fields>';

SELECT @xml.value(N'(/fields/fields[@mandat="true"]/@name)[1]',N'nvarchar(max)') AS Mandant_Name

UPDATE 2: More than one <fields> with @mandat="true"

Just try my first solution with a predicate in .nodes() :

DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="b" active="2" />
  <fields name="c" active="3" mandat="false" />
  <fields name="d" active="4" mandat="true" />
</fields>';


SELECT fld.value(N'@name',N'nvarchar(max)') AS Field_Name
      ,fld.value(N'@active',N'bit') AS Field_Active
      ,fld.value(N'@mandat',N'bit') AS Field_Mandant
FROM @xml.nodes(N'/fields/fields[@mandat="true"]') AS A(fld)

This will return only the first and the last <fields> node

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