sql-server – SQL Server .nodes()按名称命名的XML父节点
发布时间:2020-12-12 07:26:30 所属栏目:MsSql教程 来源:网络整理
导读:declare @xmlsample xml ='root solution solutionnumber1/solutionnumber productgroup productcategory price100/price titleSome product/title tax1/tax /productcategory /productgroup productcategory2 price200/price titleSome other product/title
declare @xmlsample xml = '<root> <solution> <solutionnumber>1</solutionnumber> <productgroup> <productcategory> <price>100</price> <title>Some product</title> <tax>1</tax> </productcategory> </productgroup> <productcategory2> <price>200</price> <title>Some other product</title> <tax>2</tax> </productcategory2> </solution> <solution> <solutionnumber>2</solutionnumber> <productcategory2> <price>200</price> <title>Some other product</title> <tax>2</tax> </productcategory2> </solution> </root>' SELECT --T.C.value('(./ancestor::ns1:solutionNumber)[1]','varchar(50)') AS solutionnumber ?? no clue T.C.value('(price)[1]','numeric(18,2)') AS price,T.C.value('(title)[1]','varchar(50)') AS title,T.C.value('(tax)[1]',2)') AS tax FROM @xmlsample.nodes('//node()[title]') AS T(C) 我试图在SQL Server 2008 r2中粉碎的XML的表示.我找到了“标题”节点,并获取了产品类别中我需要的值.现在我想获得“解决方案编号”,但是这可能是产品上方的一个或多个父节点,因为存在某些产品“组”. 在找到之前,我将如何通过名称(“solutionnumber”)检查父节点?谢谢你的帮助. 解决方法我的知识没有直接的方法.但是,您可以使用COALESCE进行搜索:SELECT COALESCE(T.C.value('../solutionnumber[1]','INT'),T.C.value('../../solutionnumber[1]',T.C.value('../../../solutionnumber[1]','INT')) solutionnumber,T.C.value('(price)[1]',2)') AS tax FROM @xmlsample.nodes('//node()[title]') AS T ( C ) 注意< solutionnumber>真的是一个祖先的兄弟,而不是祖先本身. 此解决方案要求您提前知道最大深度. 如果你宁愿前进而不是后退,你也可以使用这个解决方案: SELECT solutionNodes.solutionNode.value('solutionnumber[1]','INT') AS solutionnumber,2)') AS tax FROM @xmlsample.nodes('//solution') AS solutionNodes (solutionNode) CROSS APPLY (SELECT solutionNodes.solutionNode.query('.')) solutions(solutionXML) CROSS APPLY solutions.solutionXML.nodes('//node()[title]') T ( C ) 它使用< solutionnumber>的事实. tag是< solution>的直接子代.标签.首先,所有<解决方案>标签被找到.比所有的标题后代都有交叉申请.因为您无法在节点上使用节点函数,所以在它们之间会计算“query(‘.’)”. 除了上述解决方案之外,该解决方案可以处理< solution>之间的任何距离.标记abd< title>标签. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |