Thursday, April 17, 2008

Find First and Last Day Of Each Month

The first day of each month is always 1. However if you interested to find the First and Last Date of each month using a Sql Query, here it is:

-- Return First and Last Date of a Month
DECLARE @Month smallint
SET @Month = 1

SELECT DAY(DATEADD(Month, DATEDIFF(Month, -1, getdate()) - 2, -1) + 1) as FirstDayofMonth,
DAY(DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1)) as LastDayOfMonth

If you wish to find out the Lastday of the previous month, just set @Month to 0.

DATENAME() function in SQL Server 2005

The DATENAME() is quiet a handy function if you want to return a literal form (string) of the part of the date specified.

The syntax goes like:
DATENAME ( datepart ,date )

Where :
datepart - specifies the part of the date to return
date - datetime or smalldatetime expression

USAGE:

DECLARE @Dt datetime
SET @Dt = '2008-04-15 8:34:54.713'

SELECT DATENAME(year, @Dt) as 'Year'
-- Returns 2008

SELECT DATENAME(quarter, @Dt) as 'Quarter'
-- Returns 2

SELECT DATENAME(month, @Dt) as 'Month'
-- Returns April

SELECT DATENAME(dayofyear, @Dt) AS 'Day of Year';
-- Returns 106

SELECT DATENAME(day, @Dt) AS 'Day';
-- Returns 15

SELECT DATENAME(week, @Dt) AS 'Week';
-- Returns 16

SELECT DATENAME(weekday, @Dt) AS 'Weekday';
-- Returns Tuesday

SELECT DATENAME(hour, @Dt) AS 'Hour';
-- Returns 8

SELECT DATENAME(minute, @Dt) AS 'Minutes';
-- Returns 34

SELECT DATENAME(second, @Dt) AS 'Seconds';
-- Returns 54

SELECT DATENAME(millisecond, @Dt) AS 'Milliseconds';
-- Returns 713