Friday, October 20, 2006

First/Last Day of a month

CREATE FUNCTION FirstDayOfMonth(@year int, @month int)
RETURNS DATETIME AS
BEGIN
RETURN DATEADD(MONTH, @month - 1, DATEADD(YEAR, @year - 1900, 0))
END


CREATE FUNCTION LastDayOfMonth(@year int, @month int)
RETURNS DATETIME AS
BEGIN
RETURN DATEADD(DAY, -1, DATEADD(MONTH, @month, DATEADD(YEAR, @year - 1900, 0)))
END
This works because 0 as a DateTime equals 01/01/1900, so subtracting 1900 from the year and one from the month gives the correct values.

Fuente:http://musingmarc.blogspot.com/2006/02/sql-date-processing-firstlast-day-of.html