简体   繁体   English

如何从节点获取价值? SQL Server XML dml

[英]How to get value from node? SQL Server XML dml

@x xml:'
<a number="1">
 <b>1</b>
</a>'

I want use query() to get value (can't use value() )我想使用query()获取值(不能使用value()

@x.query('string(/a[1]/b[1])') 

is ok.没问题。

@x.query('string(/a[@number="1"]/b)') 

throws an error.引发错误。

Do you have any solution?你有什么解决办法吗? I want use [@number="1"] to get value.我想使用[@number="1"]来获取价值。

你可以试试这个。

@x.query('string( (/a[@number="1"]/b)[1])') 

In most cases one wants to read more than one value from a given node.在大多数情况下,人们希望从给定节点读取多个值。 You can use a combination of .nodes() (very related to .query() , but returning a derived table) and .query() or .value() like here:您可以使用.nodes() (与.query()非常相关,但返回派生表)和.query().value()如下所示:

DECLARE @x xml=
N'<a number="1">
 <b>1</b>
</a>';

SELECT MyA.value(N'(b/text())[1]','int') AS ReadTheValue
      ,MyA.query(N'b') QueryTheValue
FROM @x.nodes(N'/a[@number="1"]') AS A(MyA); 

You can pass in the search value as a variable like here:您可以将搜索值作为变量传入,如下所示:

DECLARE @SearchNumber INT=1;
SELECT MyA.value(N'(b/text())[1]','int') AS ReadTheValue
      ,MyA.query(N'b') QueryTheValue
FROM @x.nodes(N'/a[@number=sql:variable("@SearchNumber")]') AS A(MyA); 

If you need nothing else then the value through .query() go with the solution provided by Serkan Aslan.如果您不需要其他任何东西,那么.query()的值与 Serkan Aslan 提供的解决方案一起使用。 You were just missing to ensure the inner experession to be singleton.您只是缺少确保内部表达成为单身人士。

But I must admit, that I have no idea, why one should need this...但我必须承认,我不知道为什么需要这个......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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