How do you use the ISDATE function to check if a string is a valid date?
Posted by KarenKg
Last Updated: July 20, 2024
In SQL Server, the ISDATE function is used to determine whether a given expression can be converted to a date data type. It returns 1 if the expression is a valid date, otherwise it returns 0. The function can be applied to strings, numbers, and other expressions that represent date values. Here's how to use the ISDATE function:
Syntax
ISDATE(expression)
- expression: This is the value that you want to check. It can be a string or another type that you expect might represent a date.
Example Usage
1. Basic Check:
SELECT ISDATE('2023-10-15') AS IsValidDate;  -- Returns 1
SELECT ISDATE('10/15/2023') AS IsValidDate;  -- Returns 1
SELECT ISDATE('InvalidDateString') AS IsValidDate;  -- Returns 0
2. Table Example: Assume you have a table named Events with a column EventDate that contains string representations of dates.
CREATE TABLE Events (
    EventName NVARCHAR(100),
    EventDate NVARCHAR(50)
);

INSERT INTO Events (EventName, EventDate) VALUES
('Event 1', '2023-10-15'),
('Event 2', 'InvalidDate'),
('Event 3', '10/15/2023');

SELECT EventName, EventDate, ISDATE(EventDate) AS IsValidDate
FROM Events;
Key Considerations
- The ISDATE function is influenced by the current language and the date format settings of the SQL Server instance. Therefore, it’s important to make sure the string conforms to the expected date format. - While ISDATE can check if a string is valid for conversion to a date type, it does not actually convert it. If you need to convert the string to a date or catch errors for full validation, consider using TRY_CONVERT or TRY_CAST along with ISDATE for more robust error handling.
Note
In recent versions of SQL Server (SQL Server 2012 and later), you might also use TRY_CONVERT to attempt a conversion and return NULL if it fails, which allows you to handle invalid date formats more gracefully than with ISDATE.
SELECT TRY_CONVERT(DATE, EventDate) AS ValidatedDate
FROM Events;
This approach gives you more control, so consider using it if you need to work with dates extensively.