SQL在查询时将NVARCHAR转换为日期时间

时间:2015-06-18 11:25:09

标签: sql sql-server type-conversion

我有一个SQL函数来检索数据,但我在数据库上遇到问题,在将该字段设为NVARCHAR而不是DATETIME之前处理它的人,所以现在我无法对日期进行整理或选择范围之间的数据。

假设我有一个查询:

Select order_confirmation.oc_number as oc,
order_confirmation.count as cnt,
order_confirmation.status as stat,
order_confirmation.po_number as pon,
order_summary.date_delivered as dd,
order_summary.delivery_quantity as dq,
order_summary.is_invoiced as iin,
order_summary.filename as fn,
order_summary.invoice_number as inum,
order_summary.oc_idfk as ocidfk,
order_summary.date_invoiced as di
FROM
order_confirmation,order_summary
where order_confirmation.id = order_summary.oc_idfk
order by order_summary.date_delivered DESC

我想将order_summary.date_delivered转换为DATETIME格式,以便ORDER BY语句可以正常工作。请注意,我不想永久更改数据库结构上的数据类型,只在查询中。我尝试搜索并尝试其他解决方案,但不会工作加上我的工作还不熟悉SQL Server。

由于

助手:

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:3)

在您的订单子句中使用:

order by convert(datetime,order_summary.date_delivered, X)

其中X = 100,101,102 ......取决于您希望的格式

Here您可以看到转换功能的更多详细信息

答案 1 :(得分:-1)

<强>已更新 基于Iconic的优点并希望纠正您的溢出问题使用格式105与您的CONVERT

Select order_confirmation.oc_number as oc,
order_confirmation.count as cnt,
order_confirmation.status as stat,
order_confirmation.po_number as pon,
order_summary.date_delivered as dd,
order_summary.delivery_quantity as dq,
order_summary.is_invoiced as iin,
order_summary.filename as fn,
order_summary.invoice_number as inum,
order_summary.oc_idfk as ocidfk,
order_summary.date_invoiced as di
FROM
order_confirmation,order_summary
where order_confirmation.id = order_summary.oc_idfk
order by CONVERT(datetime, order_summary.date_delivered, 105) DESC