SQL Server字符串到日期转换

时间:2011-07-27 19:24:19

标签: sql-server sql-server-2005 datetime formatting

我有以下查询:

SELECT  o.OrderNumber,
    cast(o.DateOrdered as datetime),
    cast(oi.Category as varchar(max))

 FROM   Orders o
    LEFT OUTER JOIN OrderItems oi ON oi.OrderID = o.uid
    LEFT OUTER JOIN OrderAddresses oa ON oa.OrderID = o.uid

 WHERE O.DateOrdered LIKE '6%2011%' AND (oa.Type = '4') AND (oa.Country = 'US')

 GROUP BY cast(oi.Category as varchar(max)), cast(o.DateOrdered as datetime), o.OrderNumber

我无法将datetime格式化为mm/dd/yyyy。无论我尝试过什么,我都会像YYYY-MM-DD 00:00:00:000一样。我必须在语法中忽略一些简单的东西,希望有人能指出我正确的方向吗? (SQL Server 2005)

谢谢!

3 个答案:

答案 0 :(得分:1)

尝试使用CONVERT代替CAST

CONVERT(VARCHAR(10), o.DateOrdered , 101)

所以GROUP BY语句看起来像:

GROUP BY CAST(oi.Category as varchar(MAX)), CONVERT(VARCHAR(10), o.DateOrdered , 101), o.OrderNumber 

答案 1 :(得分:1)

CAST只会转换数据类型 - 但它不能让您选择任何格式。

要进行格式化,您需要使用CONVERT代替(有关详细信息,请参阅MSDN Books Online):

尝试

SELECT CONVERT(VARCHAR(25), GETDATE(), 101)

应该以您正在寻找的格式呈现当前日期。

答案 2 :(得分:0)

看起来DateOrdered是VARCHAR

请尝试

SELECT  o.OrderNumber,
    CONVERT(VARCHAR(25),cast(o.DateOrdered as datetime), 101),
    cast(oi.Category as varchar(max))

 FROM   Orders o
    LEFT OUTER JOIN OrderItems oi ON oi.OrderID = o.uid
    LEFT OUTER JOIN OrderAddresses oa ON oa.OrderID = o.uid

 WHERE O.DateOrdered LIKE '6%2011%' AND (oa.Type = '4') AND (oa.Country = 'US')

 GROUP BY cast(oi.Category as varchar(max)), CONVERT(VARCHAR(25),cast(o.DateOrdered as datetime), 101), o.OrderNumber