Search code examples
t-sqlvalidationdatetimevarcharsap-ase

Best method for varchar date validation in Sybase (T-SQL)?


I have a stored procedure which takes as its parameter a varchar which needs to be cast as a datetime for later use:

SET @the_date = CAST(@date_string AS DATETIME)

I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?

NB: using Sybase ASE 12.5.3, there is no ISDATE function


Solution

  • I'm having a similar issue. You might be able to do something like this:

    SET arithabort arith_overflow off
    SET @the_date = CAST(@date_string AS DATETIME)
    IF @the_date is NULL
        set @the_date = getdate()
    SET arithabort arith_overflow on
    

    However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.