This article is based on the a question from Jr. Developer at my company. He works with the system, where we import CSV file in our database. One of the fields in the database is DATETIME field. Due to architecture requirement, we insert all the CSV fields in the temp table which has all the fields VARCHAR. We validate all the data first in temp table (check for inconsistency, malicious code, incorrect data type) and if passed validation we insert them in the final table in the database. Let us learn about ISDate function in this blog post.
We always checked DATETIME field for incorrect data type. One of the user input dates as 30/2/2007. The date was successfully inserted in the temp table but while inserting from temp table to final table it crashed with error. We had now task to validate incorrect date value before we insert in the final table. A junior Developer asked me how can he do that? We check for incorrect data type (varchar, int, NULL) but this is incorrect date value. Regular expression works fine with them because of mm/dd/yyyy format.
After a long history of the problem the solution is very simple. We now use ISDATE() function to validate if the date is valid.
Examples:
----Invalid date SELECT ISDATE('30/2/2007')
RETURNS : 0 (Zero)
----Valid date SELECT ISDATE('12/12/2007')
RETURNS : 1 (ONE)
----Invalid DataType SELECT ISDATE('SQL')
RETURNS : 0 (Zero)
Reference : Pinal Dave (https://darkslategrey-bat-805937.hostingersite.com)