這兩種日期格式轉換得很好。默認的convert
算法做了一個相當體面的工作,即靈活地處理它給出的內容。和一個null
字符串,正如我前面評論, will always convert to a
null datetime value: per the standard, any expression that involving
null yields
null`。
我懷疑你有數據問題。最有可能的垃圾字符,如嵌入的CR,LF或CR + LF(換行符)。 HT(製表符)字符也似乎打破convert()
。您(或您的DBA)可能需要執行數據清理以擺脫垃圾字符。或者你需要解決這個問題並編寫一個醜陋的表達式來修復運行時的錯誤數據。
像這樣的查詢應該找出問題的數據:
select myCruftyDateTimeColumn,count(*)
from foo
where myCruftyDateTimeColumn is not null
-- m/d/yyyy hh:mm:ss AM format
and myCruftyDateTimeColumn not like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [AP]M'
and myCruftyDateTimeColumn not like '[0-9][0-9]/[0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [AP]M'
and myCruftyDateTimeColumn not like '[0-9]/[0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [AP]M'
-- month d, yyyy alternatives, 2 digit days
and myCruftyDateTimeColumn not like 'January [0-9][0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'February [0-9][0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'March [0-9][0-9], [0-9][0-9][0-9][0-9]'
and ...
and myCruftyDateTimeColumn not like 'October [0-9][0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'November [0-9][0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'December [0-9][0-9], [0-9][0-9][0-9][0-9]'
-- month d, yyyy alternatives, 2 digit days
and myCruftyDateTimeColumn not like 'January [0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'February [0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'March [0-9], [0-9][0-9][0-9][0-9]'
and ...
and myCruftyDateTimeColumn not like 'October [0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'November [0-9], [0-9][0-9][0-9][0-9]'
and myCruftyDateTimeColumn not like 'December [0-9], [0-9][0-9][0-9][0-9]'
group by myCruftyDateTimeColumn
order by 1
您可能需要加載一個臨時表中的結果,然後,從該
select *,convert(varbinary,myCruftyDateTimeColumn)
from #bad_data
,以確定到底是什麼假的字符是。
數據是否將'null'表示爲字符串,或者是記錄實際上是否爲NULL? – JNK 2011-05-24 17:04:56
它實際上是NULL – mattgcon 2011-05-24 17:17:58