用于XML路径时如何在根元素中添加属性值?

时间:2018-07-20 09:34:53

标签: sql-server xml sql-server-2008 tsql

我有此SQL,它可以工作:

set nocount on 

DECLARE
    @OrderID VARCHAR(200) = '13095314100';

declare @eOrder Table
(
  colOrderId  varchar(20),
  colDeliveryCountryCode varchar(20)
 )

insert into @eOrder values ('13095314100', 'SE')


SELECT 
    'name'  AS 'Val/@n', Sender.name AS Val

FROM @eOrder E
  inner join 
    (
       select  '12345' SenderID,     'KappAhl Sverige AB' "name",  'Idrottsvägen 14' "address1",   null address2,       '431 24' ZipCode,   'MÖLNDAL' City, 'SE' Country,  '010-138 87 11' phone
       union
       select  '12345',          'KappAhl Shop Online',       'c/o KappAhl OY',             'Unikkotie 3 C',    '01300'     ,  'VANTAA',        'PL',        '0753 267 881'    
    ) Sender
    on E.colDeliveryCountryCode = Sender.Country

WHERE colOrderId = @OrderID
FOR XML PATH('Sender');

我得到了预期的输出:

<Sender><Val n="name">KappAhl Sverige AB</Val></Sender>

但是如何将SenderID作为属性添加到我的Sender标签中?

想要的XML输出:

<Sender SenderID="12345" ><Val n="name">KappAhl Sverige AB</Val></Sender>

1 个答案:

答案 0 :(得分:2)

Sender.SenderID as '@SenderID'添加到您的选择中:

SELECT Sender.SenderID as '@SenderID',
    'name'  AS 'Val/@n', Sender.name AS Val

结果:

enter image description here