Parsing nested XML into SQL table

前端 未结 3 1965
南笙
南笙 2020-12-29 17:22

What would be the right way to parse the following XML block into SQL Server table according to desired layout (below)? Is it possible to do it with a single SELECT statemen

3条回答
  •  失恋的感觉
    2020-12-29 18:16

    You can make use of a numbers table to pick the first, second, third etc row from the child elements. In this query I have limited the rows returned to the number if dates provided. If there are more values or descriptions than dates you have to modify the join to take that into account.

    declare @XML xml = '
    
      some value
      other value
      
        2011-02-01T00:00:00
        2011-03-01T00:00:00
        2011-04-01T00:00:00
      
      
        0.019974
        0.005395
        0.004854
      
      
        this is row 1
        this is row 2
        this is row 3
      
    '
    
    ;with Numbers as
    (
      select number
      from master..spt_values
      where type = 'P'
    )
    select T.N.value('Parameter1[1]', 'varchar(50)') as Parameter1,
           T.N.value('Parameter2[1]', 'varchar(50)') as Parameter2,
           T.N.value('(Dates/dateTime[position()=sql:column("N.Number")])[1]', 'datetime') as Dates,
           T.N.value('(Values/double[position()=sql:column("N.Number")])[1]', 'float') as [Values],
           T.N.value('(Description/string[position()=sql:column("N.Number")])[1]', 'varchar(max)') as [Description]
    from @XML.nodes('/ObjectData') as T(N)
      cross join Numbers as N
    where N.number between 1 and (T.N.value('count(Dates/dateTime)', 'int'))
    

提交回复
热议问题