你的邏輯看起來是正確的,適用於給定的數據。不過,我敢打賭,你有一些不好的數據。
試試這個:
DECLARE @container_events table (PK int, move varchar(14))
SET NOCOUNT ON
INSERT INTO @container_events VALUES (1,'20090226115644')
INSERT INTO @container_events VALUES (2,'20090226116644')
INSERT INTO @container_events VALUES (3,'20090227010203')
INSERT INTO @container_events VALUES (4,'20090228010203')
INSERT INTO @container_events VALUES (5,'20090229010203')
SET NOCOUNT OFF
---list all bad dates
SELECT
SUBSTRING(move,1,4) + '-' + SUBSTRING(move,5,2) + '-' + SUBSTRING(move,7,2) + ' ' + SUBSTRING(move,9,2) + ':' + SUBSTRING(move,11,2) + ':'+SUBSTRING(move,13,2) as BadDatesOnly, move
FROM @container_events
where ISDATE(SUBSTRING(move,1,4) + '-' + SUBSTRING(move,5,2) + '-' + SUBSTRING(move,7,2) + ' ' + SUBSTRING(move,9,2) + ':' + SUBSTRING(move,11,2) + ':'+SUBSTRING(move,13,2))=0
---list all bad dates
SELECT
CONVERT(datetime,SUBSTRING(move,1,4) + '-' + SUBSTRING(move,5,2) + '-' + SUBSTRING(move,7,2) + ' ' + SUBSTRING(move,9,2) + ':' + SUBSTRING(move,11,2) + ':'+SUBSTRING(move,13,2)) as GoodDatesOnly, move
FROM @container_events
where ISDATE(SUBSTRING(move,1,4) + '-' + SUBSTRING(move,5,2) + '-' + SUBSTRING(move,7,2) + ' ' + SUBSTRING(move,9,2) + ':' + SUBSTRING(move,11,2) + ':'+SUBSTRING(move,13,2))=1
OUTPUT:
BadDatesOnly move
------------------- --------------
2009-02-26 11:66:44 20090226116644
2009-02-29 01:02:03 20090229010203
(2 row(s) affected)
GoodDatesOnly move
----------------------- --------------
2009-02-26 11:56:44.000 20090226115644
2009-02-27 01:02:03.000 20090227010203
2009-02-28 01:02:03.000 20090228010203
(3 row(s) affected)
使用ISDATE (Transact-SQL)功能,您可以確定日期是否有效。因此,您可以過濾掉查詢中的錯誤行,或查找錯誤的行並修復它們等等,這取決於您如何處理錯誤的數據。
你可以發佈案例的代碼和轉換,所以我們可以知道你有什麼樣的錯誤 – vodkhang 2010-05-21 08:52:33