SQL:按XML定义查找select列的列名

时间:2013-10-21 09:59:57

标签: sql xml sql-server-2008 unpivot

我在SQL Server 2008中有两个表:

Definitions(ID, XML)
Data(DataID, DefinitionID, COL1, COL2, ..)

XML看起来像这样:

<definition>
    <field columnname="COL1" fieldname="FirstName" />
    <field columnname="COL2" fieldname="Surname" />
</definition>

我需要的是这样的事情:

DataID, Surname, FirstName
1       Adams    Adam     
2       Llama    John     
3       Kenny    Lorna

我试图使用交叉应用从xml获取列并从中取消数据以从数据表中获取数据 - 但无法将它们合并在一起...是否有任何理智的方法?

我在尝试什么:

select distinct 
       Ids.Id.value('@columnname', 'nvarchar(50)') as ide,
       Ids.Id.value('@fieldname', 'nvarchar(50)') as name
   from Definitions 
   cross apply Xml.nodes('//field') as Ids(id) 

select col, value from 
   (SELECT COL1, COL2  FROM Data) d
   UNPIVOT 
   (value for col IN (COL1, COL2)) AS newdata
;

1 个答案:

答案 0 :(得分:1)

您可以使用case检查XML应该使用哪个列。

select D.DataID,
       case DD.XML.value('(/definition/field[@fieldname="FirstName"]/@columnname)[1]', 'sysname')
         when 'COL1' then D.COL1
         when 'COL2' then D.COL2
       end as FirstName,
       case DD.XML.value('(/definition/field[@fieldname="Surname"]/@columnname)[1]', 'sysname')
         when 'COL1' then D.COL1
         when 'COL2' then D.COL2
       end as Surname
from Data as D
  inner join Definitions as DD
    on D.DefinitionID = DD.ID