考虑下表:
订单
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>
问题是,XML文件中的ShipDate
值必须采用M/DD/YYYY H:mm:ss PM
格式。如何将XML文件中ShipDate
的输出更改为所需格式?
非常感谢任何帮助!
答案 0 :(得分: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>
答案 1 :(得分: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>