簡體   English   中英

使用SQL查詢的XML標簽形成

[英]XML tag formation using sql query

我的Xml看起來像這樣:

biometrictDate, biometricID,dateOfBirth, firstName, gender, 
lastName, consumerUserId, MedicalHeightValue

是表中的所有列。

<Assessment biometrictDate="20120305 08:03:00" biometricID="74330759" 
            dateOfBirth="1975-04-08" firstName="BRYAN" gender="M" lastName="HAYES" 
            consumerUserId="120004223500"> 
    <HealthAttribute>
        <Identifier>MedicalHeightValue</Identifier>
        <Value>67</Value>
    </HealthAttribute>
</Assessment>

MedicalHeightValue應該單獨放在HealthAttribute標記之間,可使用以下查詢完成:

select C.Value, C.Identifier
from TableA
    outer apply (values
        ('MedicalHeightValue', MedicalHeightValue) ) as C(Identifier, Value)
for xml path('HealthAttribute')

現在,我只想在評估標簽中添加以下列

{biometrictDate, biometricID, dateOfBirth, firstName, gender, lastName, consumerUserId} 

有什么幫助嗎?

新的XML應該如下所示:

<Assessment biometrictDate="20120305 08:03:00" biometricID="74330759" 
            dateOfBirth="1975-04-08" firstName="BRYAN" gender="M" lastName="HAYES" 
            consumerUserId="120004223500"> 
   <HealthAttribute> 
      <Identifier>MedicalHeightValue</Identifier> 
      <Value>67</Value> 
   </HealthAttribute> 
</Assessment>

首先,很難理解您想要獲得什么。 我想我已經從您的問題和您以前的問題 (順便說一句,仍然沒有被接受的答案)中弄清楚了。

這是您需要的查詢:

select
    A.biometrictDate, A.biometricID, A.dateOfBirth,
    A.firstName, A.gender, A.lastName, A.consumerUserId,
    (
        select *
        from (values
            ('MedicalHeightValue', A.MedicalHeightValue),
            ('MedicalWeightValue', A.MedicalWeightValue)
        ) as V(Identifier, Value)
        for xml path('HealthAttribute'), type
    )
from table1 as A
for xml raw('Assessment')

您也可以這樣做,以更好地控制名稱:

select
    A.biometrictDate as [@biometrictDate],
    A.biometricID as [@biometricID],
    A.dateOfBirth as [@dateOfBirth],
    A.firstName as [@firstName],
    A.gender as [@gender],
    A.lastName as [@lastName],
    A.consumerUserId as [@consumerUserId],
    (
        select *
        from (values
            ('MedicalHeightValue', A.MedicalHeightValue),
            ('MedicalWeightValue', A.MedicalWeightValue)
        ) as V(Identifier, Value)
        for xml path('HealthAttribute'), type
    )
from table1 as A
for xml path('Assessment')

sql小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM