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 (1 vote)
23 Nov 2012CPOL 5.7K   11  
Just a function to make populating a datetime variable easier!

Introduction

I have been writing SQL stored procedures for a while now, but whilst I am testing out the code before creating the stored procedure, I always found declaring and setting a date to be a pain!

So I decided to create a function that you enter the year month day and it converts this to a date.

So here it is.... The code

SQL
CREATE FUNCTION [dbo].[fn_BuildDate] (@Year int, @Month int, @Day int)
RETURNS DATETIME
BEGIN
DECLARE @vInputDate DATETIME
SET @vInputDate = dateadd(day, @Day - 1, dateadd(month, @Month - 1, dateadd(year, @Year-1900, 0)))
RETURN @vInputDate
END

Using the code

To use the function is nice and easy in comparison to normally casting a date

SQL
DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(2012,11,23)

 

Hope it helps someone else! 

License

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