[英]Query xml using sql server
i am new to xml queries. 我是xml查询的新手。 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. 现在,我需要找到manadt是真实的所有字段名称。 How can i query xml using sql server.
我如何使用sql server查询xml。 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. 您的问题不是很清楚,尤其是标签(
sql, xml, c#-4.0
),但是我从问题的文本中得知,您需要查询SQL Server中XML的内容。
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
If you want to read the value of @name
of the fields-node, where @mandat
is "true" , do it like this: 如果要读取fields-node的
@name
的值(其中@mandat
为“ true”) ,请执行以下操作:
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
<fields>
with @mandat="true"
<fields>
与@mandat="true"
Just try my first solution with a predicate in .nodes()
: 只需使用
.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 这将仅返回第一个和最后一个
<fields>
节点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.