简体   繁体   English

T-SQL 2008将日期和时间字符串转换为datetime

[英]T-SQL 2008 Convert Date and time string to datetime

I have two columns in my table, one to capture time and one to capture date. 我的表中有两列,一列用于捕获时间,一列用于捕获日期。 Unfortunately, both are varchar(). 不幸的是,两者都是varchar()。 I need to take the two fields, concatenate them together, and then convert them to datetime. 我需要将两个字段合并在一起,然后将它们转换为日期时间。

I am trying to accomplish that with this: 我正在努力做到这一点:

select CONVERT(datetime,(select txt_returned_date+' '+CONVERT(varchar(20),CONVERT(TIME,txt_time_returned))),126) 
from table_name

I am getting this error message: 我收到此错误消息:

Conversion failed when converting date and/or time from character string.

The date is being captured as "20130308" as a string. 该日期作为字符串被捕获为“ 20130308”。 Time is being captures as "4:27 PM" as a string 时间以字符串形式捕获为“ 4:27 PM”

What I am doing here is converting the string of the time to TIME, then back to varchar. 我在这里所做的是将时间的字符串转换为TIME,然后再转换回varchar。 Then I am concatenating them together. 然后,我将它们串联在一起。 This works by itself, but once I introduce the CONVERT(datetime) to the whole query, it is giving me the error. 它本身可以工作,但是一旦我在整个查询中引入了CONVERT(datetime),它就会给我错误。

Any help to try to accomplish this is helpful. 尝试完成此操作的任何帮助都是有帮助的。 Thanks! 谢谢!

You can concatenate the DATE and TIME values together once they have been converted to a DATETIME. 一旦将DATE和TIME值转换为DATETIME,就可以将它们连接在一起。 Here's a sample to play with that shows concatenating a DATE column and a TIME column that have been stored as VARCHAR: 这是一个示例,该示例显示了将已存储为VARCHAR的DATE列和TIME列连接在一起:

-- Set up some variables to test with
DECLARE @myTime TIME = GETDATE()
    , @myDate DATE = GETDATE()
    , @myTimeTxt VARCHAR(16)
    , @myDateTxt VARCHAR(10);

-- Initialize your variables
SELECT @myTimeTxt = @myTime
    , @myDateTxt = @myDate;

-- Display your separated values
SELECT @myDateTxt, @myTimeTxt;

-- Display your concatenated value
SELECT CAST(@myDateTxt AS DATETIME) + CAST(CAST(@myTimeTxt AS TIME) AS DATETIME);

You can use this option 您可以使用此选项

DECLARE @date date = '20010101',
        @time time = '01:01:01'

SELECT CAST(@date AS datetime) + @time

Result: 2001-01-01 01:01:01.000 结果: 2001-01-01 01:01:01.000

Demo on SQLFiddle 关于SQLFiddle的演示

Are you using SQL 2012? 您正在使用SQL 2012吗? If so you may be able to use the datetimedromparts function to achieve this. 如果是这样,您也许可以使用datetimedromparts函数来实现此目的。 If not for this specific example, it's always good to know for the future :) 如果不是这个特定的例子,那么对未来了解总是一件好事:)

http://technet.microsoft.com/en-gb/library/hh213233.aspx http://technet.microsoft.com/zh-CN/library/hh213233.aspx

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

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