65.9K
CodeProject is changing. Read more.
Home

Build a Date Function

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Nov 23, 2012

CPOL
viewsIcon

5822

downloadIcon

16

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

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

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

 

Hope it helps someone else!