Dealing with custom date formats in T-SQL
Should I be formatting dates on the database side? What tools can I use in SQL Server to format and parse dates? This article helps you decide which one best suits your needs.
2012-03-23
24,137 reads
--Gets number of days for a month. Leap years taken in consideration. CREATE FUNCTION dbo.fnGetMonthDays(@myDate DATE) RETURNS INT AS BEGIN DECLARE @isLeap INT = 0 IF (YEAR(@myDate) % 400 = 0 OR (YEAR(@myDate) % 4 = 0 AND YEAR(@myDate) % 100 !=0)) SET @isLeap=1 DECLARE @month INT = MONTH(@myDate) DECLARE @days INT SELECT @days = CASE WHEN @month=1 THEN 31 WHEN @month=2 THEN 28 + @isLeap WHEN @month=3 THEN 31 WHEN @month=4 THEN 30 WHEN @month=5 THEN 31 WHEN @month=6 THEN 30 WHEN @month=7 THEN 31 WHEN @month=8 THEN 31 WHEN @month=9 THEN 30 WHEN @month=10 THEN 31 WHEN @month=11 THEN 30 WHEN @month=12 THEN 31 END RETURN @days END