将8长度varchar转换为datetime

时间:2015-04-28 16:40:30

标签: sql converter

我将varchar列作为数据集:

20110712
20141229
20100222
20140408
20131117
20130912
20140702
20110405

需要转换datetime数据类型。我试过:CONVERT(date,column_name)但它返回错误:

 Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

我如何确保这可行?

1 个答案:

答案 0 :(得分:1)

如果您的日期是varchar,那么您应该能够使用CONVERT(DATE,[date_field],112)

DECLARE @dates TABLE 
  (
    [date] varchar(10)
  )

INSERT INTO @dates([date])
VALUES('20110712'),('20141229'),('20100222'),('20140408'),('20131117'),('20130912'),('20140702'),('20110405')

SELECT CONVERT(date,[date],112) 
FROM @dates