使用SQL自动生成XML-如何在不使用root()的情况下在一组相似项周围获取外部标记?

时间:2014-06-26 19:18:40

标签: sql xml

理想情况下,我想要一个类似于下面的XML文件,但到目前为止,我的查询不生成OrderRequests的标记,而只生成OrderRequest。下面是我使用的查询和需要生成的XML。

查询:

declare @xml XML;
declare @RequestFileHeader table
(
ClientCode varchar(10),
CreateTime varchar(40),
BatchNumber int
);

insert into @RequestFileHeader values('CMG','2013-09-16T00:20:13.7306775-07:00',
CAST(RAND() * 1000000 AS INT) ) 

select RequestFileHeader.*, 

 OrderRequest.TransactionTime,
     (OrderRequest.ReferenceNumber -1000000+ CAST(RAND() *1000000 AS      INT))
 ReferenceNumber,
      'False' as IsRush, ShippingAddress.*
    from    
    @RequestFileHeader RequestFileHeader,
 RbcRequest OrderRequest,
 RbcOrderShippingAddress ShippingAddress-- , RbcRequest OrderRequests
 where (ShippingAddress.RequestId = OrderRequest.RequestId)



for xml AUTO , root('TransactionRequest'), Elements


 GO

XML:

<OrderRequests>
 <OrderRequest>
  <ReferenceNumber>647433081</ReferenceNumber> 
  <TransactionTime>2014-04-07T04:35:00</TransactionTime> 
  <IsRush>false</IsRush> 
  <ShippingAddress>
  <Name>ROGER RAI</Name> 
  <Address1>18855 54A AVE</Address1> 
  <Address2 /> 
  <Address3 /> 
   <City>SURREY</City> 
  <Province>BC</Province> 
  <PostalCode>V3S6R4</PostalCode> 
  <HomePhone>6046008564</HomePhone> 
  <BusinessPhone>6047247883</BusinessPhone> 
  </ShippingAddress>
  <ProgramType>AV</ProgramType> 
  <Comments /> 
 <Items>
   <Item>
      <Sku>CC03327-SLV</Sku> 
      <ProductCode>AA1346</ProductCode> 
      <Quantity>1</Quantity> 
   </Item>
 </Items>
 </OrderRequest>

1 个答案:

答案 0 :(得分:0)

将您已有的查询嵌入到创建根节点的查询中。您还需要将type指令添加到现有查询中。

select (
       -- Replace this with your existing query.
       select *
       from T
       for xml auto, root('OrderRequest'), elements, type
       )
for xml path('OrderRequests')