且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 SQL Server 中将 varchar 转换为日期时间

更新时间:2023-01-29 07:40:10

OP 想要 mmddyy,而普通的转换将无法解决这个问题:

OP wants mmddyy and a plain convert will not work for that:

select convert(datetime,'12312009')

Msg 242, Level 16, State 3, Line 1 
The conversion of a char data type to a datetime data type resulted in 
an out-of-range datetime value

试试这个:

DECLARE @Date char(8)
set @Date='12312009'
SELECT CONVERT(datetime,RIGHT(@Date,4)+LEFT(@Date,2)+SUBSTRING(@Date,3,2))

输出:

-----------------------
2009-12-31 00:00:00.000

(1 row(s) affected)