티스토리 뷰

Computer/Databases

[MSSQL2005] Data Type Conversion Error

인생이글케쉬우냐 2009. 10. 13. 17:28
며칠전에 YYYYMMDDhhmmss형태의 날짜 스트링을 데이트타입으로 변환하는동안에
데이터가 얼마 없을때는 무리없이 잘 돌던게..
쿼리 대상 데이터가 많아지자 아래와 같은 에러메세지를 가뿐히 보여주며 문제가 생겼댄다.

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.

어우..
머가 문젤까.. 진짜 고민 많이 했다.
getDate()를 문자로 convert하고 다시 datetime으로 변환하면 잘 되드만..
여기저기 검색해본 결과 아래와 같은 mssql server helper라는 사이트를 찾았다.
이유인 즉슨.. 데이터들중에 valid하지 않은 값이 있었다.
예를 들면.. 20091000121212 이런경우에..
날짜는 0일이라는게 없지 않은가..

걍 알아서 변환 잘 좀 해주지.. 싶지만.. 모.. 그걸 규칙없이 처리해줄리도 만무하고..
결국은 ISDATE( 'YYYYMMDD hh:mm:ss') 라는 함수를 찾아냈다.
블아보!
이 함수는 해당 값이 유효한 값인지 판별 한 이후에,
유효한 값이면 1을, 유효하지 않으면 0을 토해낸다.


[아래출처 : http://www.sql-server-helper.com/error-messages/msg-242.aspx]

SQL Server Error Messages > Msg 242 - The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
SQL Server Error Messages - Msg 242 - The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

SQL Server Error Messages - Msg 242

Error Message:

Server: 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.

Causes:

This error occurs when trying to convert a string date value into a DATETIME data type but the date value contains an invalid date.  The individual parts of the date value (day, month and year) are all numeric but together they don’t form a valid date.

To illustrate, the following SELECT statements will generate the error:

SELECT CAST('02/29/2006' AS DATETIME) -- 2006 Not a Leap Year
SELECT CAST('06/31/2006' AS DATETIME) -- June only has 30 Days
SELECT CAST('13/31/2006' AS DATETIME) -- There are only 12 Months
SELECT CAST('01/01/1600' AS DATETIME) -- Year is Before 1753

Another way the error may be encountered is when the format of the date string does not conform to the format expected by SQL Server as set in the SET DATEFORMAT command.  To illustrate, if the date format expected by SQL Server is in the MM-DD-YYYY format, the following statement will generate the error:

SELECT CAST('31-01-2006' AS DATETIME)
반응형