Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / T-SQL
Alternative
Tip/Trick

Build a Date Function

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
26 Nov 2012CPOL1 min read 8K   2   2
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)


Written By
Software Developer
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionnot working Pin
Selvin26-Nov-12 4:34
Selvin26-Nov-12 4:34 
AnswerRe: not working Pin
André Kraak26-Nov-12 5:14
André Kraak26-Nov-12 5:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.