从字符串转换数据和/或时间时转换失败

时间:2016-03-17 14:42:31

标签: sql sql-server sql-server-2008

我尝试将YYYYMMDD转换为MM/DD/YY并使用下面的代码,但无效:

Convert(Varchar(8),Convert(Datetime,CONVERT(VARCHAR(8),s.birth_date)),101) DOB

有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

这应该让你开始:

;WITH CTE AS 
(
    SELECT  birth_date As IntDate,  
            LEFT(CAST(birth_date as char(8)), 4) +'-'+ SUBSTRING(CAST(birth_date as char(8)), 5, 2) +'-'+ RIGHT(CAST(birth_date as char(8)), 2) As ISOFormat,
            SUBSTRING(CAST(birth_date as char(8)), 5, 2) +'/'+ RIGHT(CAST(birth_date as char(8)), 2) +'/'+ LEFT(CAST(birth_date as char(8)), 4) As USFormat
    FROM YourTable
    WHERE birth_date > 9999999 -- must have 8 digits
    AND birth_date < 99991232 -- last supported date is 9999-12-31
)

SELECT IntDate, ISOFormat, USFormat
FROM CTE 
WHERE ISDATE(ISOFormat) = 1