Saturday, October 8, 2011

MS SQL: Create Date

There is no straight forward function in Transact-SQL to create a simple date based on year, month and day. Below we have created a userdefined function to handle this. Notice that the base date in Microsoft SQL Server is January 1st 1900. We generate the date by adding the year, month and day to the base date.

CREATE function [dbo].[sudf_Common_Date]
(
      @intYear int,
      @intMonth int,
      @intDay int
)
-- returns a datetime value for the specified year, month and day
returns datetime
as
begin
      -- Returns a date later than the base date (1.1.1900)
    return dateadd(month,((@intYear-1900)*12)+@intMonth-1,@intDay-1)
end
Olá! Se você ainda não assinou, assine nosso RSS feed e receba nossas atualizações por email, ou siga nos no Twitter.
Nome: Email:

2 kommentarer:

Anonymous said... at October 28, 2011 at 1:29 PM

You can just select CAST('2011-10-28' as datetime)

Milinda Aruna said... at August 15, 2012 at 2:01 PM

Thank you,
This was really helpful to me

Post a Comment