Days in the Month in T-SQL

Number of days in the month are same as the last day’s date number in the month. Unlike PL/SQL, in T-SQL there is no function called last_day(). Following are two methods to get it:

Method 1, if you know the date:

DECLARE @Date datetime
SET @Date = '2009/12/10'
SELECT DAY(DATEADD(d,-1,dateadd(m,1,@Date))) AS 'Last day of the month'

Method 2, if you know the year and month number:

SELECT DAY(DATEADD(D, -1, DATEADD(M, 1, CONVERT(DATETIME, (CONVERT(VARCHAR, Yer) + '-' + CONVERT(VARCHAR, Mth) + '-01'))))) AS 'Last day of the month'

http://www.bigresource.com/MS_SQL-last_day-function-s5q435mI.html

1 comment:

Labels