Default value if Cast error?

  • If I want to convert a string to a datetime, if the conversion fails, can I set it to a default value?

    So

    Update MyTable

    set myDate = cast(mystring as datetime)

    if mystring cannot be cast (or convert?) as datetime, is there some way to update it with '2008-12-31', rather than giving an erro?

  • You can use ISDATE() function with some careful considerations.

    SELECT CASE ISDATE(Col1) WHEN 1 THEN CAST(Col1 AS DATETIME) ELSE '2008-12-31' END

    FROM Table1


    N 56°04'39.16"
    E 12°55'05.25"

  • set myDate = cast(isnull(mystring,'12/31/2008') as datetime)

  • Thank you, those both worked.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply