Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / T-SQL

Build a Date Function

5.00/5 (2 votes)
26 Nov 2012CPOL1 min read 8.3K  
This is an alternative for Build a Date Function

Introduction

Using the original tip I found that passing incorrect dates like dbo.fn_BuildDate( 2012, 11, 32 ); resulted in a date (2012-12-02) without any error messages, allowing the code to continue with an incorrect date.

So I made a function that gives an error when incorrect dates are passed to it. The quickest and easiest way I could find resulted in the following function.

SQL
CREATE FUNCTION [dbo].[fn_BuildDate] (@Year int, @Month int, @Day int)
RETURNS DATETIME
BEGIN
    RETURN CONVERT( DATETIME, CAST( @Year AS VARCHAR ) + RIGHT( '0' + CAST( @Month AS VARCHAR ), 2 ) + RIGHT( '0' + CAST( @Day AS VARCHAR ), 2 ), 112 )
END

Using the code 

Using the function has not changed:

SQL
DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(2012,11,26)
But when an invalid date is passed:
SQL
DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(2012,11,32)  
You get the following error message:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The oldest date that can be used before getting an out-of-range error is:
SQL
DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(1753,1,1)

Points of Interest  

For the conversion of the date string to datetime I used CONVERT[^] instead of CAST, because with the CONVERT statement it is possible to specify the style (112 for yyymmdd) of the string to be converted. Had I used a CAST then I would have had to make sure the date string looked like '2012-11-26', causing me to use a additional two string concatenations.  But more importantly this conversion is dependent on the NLS settings of the instance the function is being run on, so using CONVERT we determine the style of the string to be converted.

History

1. - Release
2. - As per Selvin's comments, the function failed for months and days smaller than 10. The function is updated to correctly process these inputs. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)