如何在 SQL 中将文本列转换为日期时间

2021-12-22 00:00:00 datetime text sql-server-2008 sql-server

我有一列是文本:

Remarks (text, null)

样本值为

"5/21/2013 9:45:48 AM"

如何将其转换为这样的日期时间格式:

How do I convert it to a datetime format like this:

"2013-05-21 09:45:48.000"

转换的原因是我试图获取日期时间列和备注列中的日期戳之间的总小时数.我在想这样的事情:

The reason for the conversion is that I was trying to get the total number of hours between a datetime column and the date stamp in the Remarks column. I was thinking of something like this:

Remarks (text, null) - Date_Sent (datetime, null)

为了清楚起见,这些列代表客户发送查询的日期时间 (Date_Sent) 和代表对查询做出的最后响应 (Response),因此对于具有 2013-05-21 08:00:00.000"Response 值的 Date_Sent 样本如果值为 "5/21/2013 10:00:00 AM",我应该得到 2.00(2 小时)的值.不幸的是,在我正在处理的数据库中,Remarks 是一个文本,Date_Sent 是一个日期时间.

To be clear, the columns represent the datetime an inquiry by a customer was sent (Date_Sent) and the last response made by a representative regarding the inquiry (Response), so for a sample of a Date_Sent having a value of "2013-05-21 08:00:00.000" and a Response with a value of "5/21/2013 10:00:00 AM", I should get a value of 2.00 (2 hours). Unfortunately, in the database I'm working on, Remarks is a text and Date_Sent is a datetime.

推荐答案

使用 convert 样式为 101.

Use convert with style 101.

select convert(datetime, Remarks, 101)

如果你的列真的是text,你需要在转换为datetime之前先转换为varchar

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

相关文章