3

考虑下表:

订单

OrderId             Date               CustomerId
 1000       2012-06-05 20:03:12.000         51
 1001       2012-06-16 12:02:31.170         48  
 1002       2012-06-18 19:45:16.000         33

当我使用 FOR XML 提取订单数据时:

SELECT 
    OrderId AS 'Order/@Order-Id', 
    Date AS 'Order/ShipDate', 
    CustomerId AS 'Order/Customer' 
FROM Orders  
WHERE OrderId = 1000
FOR XML PATH ('')  

我得到以下结果:

<Order Order-Id="1000">
  <ShipDate>2010-02-20T16:03:12</ShipDate>
  <Customer>51</Customer>
</Order>  

问题是,ShipDateXML 文件中的值需要采用M/DD/YYYY H:mm:ss PM. 如何ShipDate将 XML 文件中的输出更改为所需的格式?

任何帮助将不胜感激!

4

2 回答 2

1

类似于 Andomar 的解决方案,但这提供了当时请求的h:mm:ss PM格式:

DECLARE @o TABLE(OrderId INT, [Date] DATETIME, CustomerId INT);

INSERT @o SELECT 1000,'2012-06-05 20:03:12',51
UNION ALL SELECT 1001,'2012-06-16 12:02:31',48  
UNION ALL SELECT 1002,'2012-06-18 19:45:16',33;

SELECT 
    OrderId AS 'Order/@Order-Id', 
    CONVERT(CHAR(10), [Date], 101) 
    + ' ' + LTRIM(RIGHT(CONVERT(CHAR(20), [Date], 22), 11))
    AS 'Order/ShipDate', 
    CustomerId AS 'Order/Customer' 
FROM @o --WHERE OrderId = 1000
FOR XML PATH ('');

结果:

<Order Order-Id="1000">
  <ShipDate>06/05/2012 8:03:12 PM</ShipDate>
  <Customer>51</Customer>
</Order>
<Order Order-Id="1001">
  <ShipDate>06/16/2012 12:02:31 PM</ShipDate>
  <Customer>48</Customer>
</Order>
<Order Order-Id="1002">
  <ShipDate>06/18/2012 7:45:16 PM</ShipDate>
  <Customer>33</Customer>
</Order>
于 2012-06-21T21:53:37.730 回答
0

这是一个如何使用CONVERT格式化日期的示例,例如mm-dd-yyyy hh:mmAM

select  convert(varchar(19), OrderDate, 110) + ' ' +
        substring(convert(varchar(19), OrderDate, 100),13,8) AS 'Order/ShipDate'
from    (
        select cast('2012-06-01 01:00' as datetime) as OrderDate
        union all select cast('2012-06-01 14:00' as datetime)
        union all select cast('2012-06-11 23:00' as datetime)
        ) Orders
for xml path ('') 

这打印:

<Order>
  <ShipDate>06-01-2012  1:00AM</ShipDate>
</Order>
<Order>
  <ShipDate>06-01-2012  2:00PM</ShipDate>
</Order>
<Order>
  <ShipDate>06-11-2012 11:00PM</ShipDate>
</Order>
于 2012-06-21T21:49:01.843 回答