2017-02-13 69 views
1

我有以下代碼來生成xml輸出。ssms生成的xml標記中的值

select 
    [FirstName] as 'SubscriberName/FirstName', 
    [Middle] as 'SubscriberName/MiddleName', 
    LastName as 'SubscriberName/LastName', 
    '123 fake street' as 'Address/Address1' 
from chp_work_area.dbo.Students1099hc 
FOR XML PATH('SubscriberInformation'), ROOT('Test') 

這是xml的輸出,並且是準確的。

<Test> 
    <SubscriberInformation> 
    <SubscriberName> 
     <FirstName>BOB</FirstName> 
     <MiddleName>G</MiddleName> 
     <LastName>CHOI</LastName> 
    </SubscriberName> 
    <Address> 
     <Address1>123 fake street</Address1> 
    </Address> 
    </SubscriberInformation> 
    <SubscriberInformation> 
    <SubscriberName> 
     <FirstName>MOLLY</FirstName> 
     <MiddleName>G</MiddleName> 
     <LastName>MORTY</LastName> 
    </SubscriberName> 
    <Address> 
     <Address1>123 fake street</Address1> 
    </Address> 
    </SubscriberInformation> 
</Test> 

我需要的最後一部分是訂戶信息列出它在標籤內的哪條記錄,以便它讀取如下。

<Test> 
    <SubscriberInformation docID="Person001"> 
    <SubscriberName> 
     <FirstName>BOB</FirstName> 
     <MiddleName>G</MiddleName> 
     <LastName>CHOI</LastName> 
    </SubscriberName> 
    <Address> 
     <Address1>123 fake street</Address1> 
    </Address> 
    </SubscriberInformation> 
    <SubscriberInformation docID="Person002"> 
    <SubscriberName> 
     <FirstName>MOLLY</FirstName> 
     <MiddleName>G</MiddleName> 
     <LastName>MORTY</LastName> 
    </SubscriberName> 
    <Address> 
     <Address1>123 fake street</Address1> 
    </Address> 
    </SubscriberInformation> 
</Test> 
+0

使用「@docID」作爲別名...你就必須做一些工作吧。通過選擇[FirstName]作爲「@docID」進行測試,您將看到我的意思。 – manderson

回答

0

嘗試這樣的事情...

SELECT ROW_NUMBER() OVER(ORDER BY [FirstName],[Middle],[LastName] ASC) AS "@docID", 
    [FirstName] as 'SubscriberName/FirstName', 
    [Middle] as 'SubscriberName/MiddleName', 
    LastName as 'SubscriberName/LastName', 
    '123 fake street' as 'Address/Address1' 
from chp_work_area.dbo.Students1099hc 
FOR XML PATH('SubscriberInformation'), ROOT('Test') 
+0

你沒有說出「Person001」,「Person002」字段是什麼,所以用它替換了docID字段。 – manderson

+0

沒有person001字段。我只是想要增量值。 – lefeal