简体   繁体   English

XML sql查询,属性作为列

[英]XML sql query , attribute as column

I need to query xml data available in server 我需要查询服务器中可用的xml数据

<root>
  <Parameter>
     <Param>APP_REG_NUMBER</Param>
     <Value>AL/T/2010/86</Value>
  </Parameter>
  <Parameter>
      <Param>SUBLINEID</Param>
      <Value>235931</Value>
  </Parameter>
</root>

This is the structure I am saving data into SQL Server, I need output as follows: 这是我将数据保存到SQL Server的结构,我需要输出如下:

Filed1     , Filed2   , APP_REG_NUMBER,  SUBLINEID
something   something , AL/T/2010/86, 235931

please do the needful 请只做那些需要的

You can use XQuery for this, but realize you are recreating key-value-pairs in XML, which negates the ability to use schemas or XQuery/XPATH in any reasonable manner. 您可以为此使用XQuery,但是意识到您正在用XML重新创建键值对,这否决了以任何合理方式使用模式或XQuery / XPATH的能力。 Consider changing the format to: 考虑将格式更改为:

<root>
    <APP_REG_NUMBER>AL/T/2010/86</APP_REG_NUMBER>
    <SUBLINEID>235931</SUBLINEID>
</root>

I digress... the query you want is: 我题外话...您想要的查询是:

DECLARE @testXml xml = N'<root>
  <Parameter><Param>APP_REG_NUMBER</Param><Value>AL/T/2010/86</Value></Parameter>
  <Parameter><Param>SUBLINEID</Param><Value>235931</Value></Parameter>
</root>'

SELECT 
    @testXml.value('(//Parameter[Param/text()="APP_REG_NUMBER"]/Value)[1]', 'nvarchar(50)') as APP_REG_NUMBER,
    @testXml.value('(//Parameter[Param/text()="SUBLINEID"]/Value)[1]', 'nvarchar(50)') as SUBLINEID

You use the //Parameter syntax to find all Parameter elements and then filter them ( [Param/text()="foobar"] ) to only those which have a child named Value that have the inner text of SUBLINEID . 您可以使用//Parameter语法来查找所有Parameter元素,然后将其过滤( [Param/text()="foobar"] ),使其仅过滤那些具有名为ValueSUBLINEID且内部文本为SUBLINEID From there, you navigate to the /Value child element and return the first result ( (query)[1] ). 从那里,您导航到/Value子元素并返回第一个结果( (query)[1] )。

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

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