Search code examples
sql-serverxmlt-sqlfor-xml

Formatting datetime values returned in a SELECT..FOR XML statement


Consider the following table:

Orders

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

When I extract the Order data using FOR XML:

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

I get the following result:

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

The problem is, the ShipDate value in the XML file needs to be in the format M/DD/YYYY H:mm:ss PM. How can I change the output of the ShipDate in the XML file to the desired format?

Any help would be greatly appreciated!


Solution

  • Similar to Andomar's solution, but this provides the requested h:mm:ss PM format for the time:

    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 ('');
    

    Results:

    <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>