简体   繁体   English

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

[英]SQL Convert NVARCHAR to Datetime on Query

I have an SQL Function that retrieves data but I have a problem on the database, the one who handled it before made the field a NVARCHAR instead of DATETIME, so now I can't sort out the date or select the data between ranges. 我有一个SQL函数可以检索数据,但是我在数据库上有一个问题,那个以前处理过的人使该字段成为NVARCHAR而不是DATETIME,所以现在我无法整理日期或在范围之间选择数据。

Supposed I have a query: 假设我有一个查询:

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

I want to convert order_summary.date_delivered to a DATETIME format so that the ORDER BY statement would work properly. 我想将order_summary.date_delivered转换为DATETIME格式,以便ORDER BY语句可以正常工作。 Please take note that I don't want to change the datatype permanently on the database structure, only in the query.I tried searching and trying other's solution but won't work plus I'm not yet familiar with SQL Server. 请注意,我不想仅在查询中永久更改数据库结构中的数据类型。我尝试搜索并尝试使用其他解决方案,但无法正常工作,而且我还不熟悉SQL Server。

Thanks 谢谢

Helpers: 助手:

在此处输入图片说明

在此处输入图片说明

on your order by clause use: 在您的order by子句中使用:

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

where X=100,101,102... depending on the format you wish to have X = 100,101,102 ...取决于您希望使用的格式

Here you can see more details for convert function 在这里您可以看到有关转换功能的更多详细信息

UPDATED Based on Iconic's good point and to hopefully correct your overflow issue Use format 105 with your CONVERT 已更新,基于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM