2016-03-17 99 views
0

轉換數據和/或時間我試圖轉換YYYYMMDDMM/DD/YY和使用下面的代碼,但沒有奏效:轉換失敗時從字符串

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

有人能幫助我。

+1

什麼'birth_date'的原始數據類型?你爲什麼將其轉換爲varchar,然後日期時間,然後再VARCHAR? – Lamak

+0

原始數據類型是Int。 – Khatra

+0

你想要的結果作爲varchar?!? – jarlh

回答

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 
+0

像冠軍一樣工作。 – Khatra

+0

很高興幫助。順便說一句,如果一個答案解決了你的問題,你應該接受它,以便其他人會知道問題已經解決 –

相關問題