I want to get the number of days in the month which the user specifies. I am using this it works for most months except for Feb and leap year. It shows 28 days and not 29. Can you solve this?
begin
declare @year int
declare @month int
select @year = 2012
select @month = DATEPART(mm,CAST('August'+ ' 2012' AS DATETIME))
select datediff(day,
dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month - 1, 0)),
dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month, 0))) as number_of_days
end
Or If not can you tell me another approach to do this. It should use @year
and @month
and the code to find the days can be any!
Gareth solution modified for SQL Server 2005
Then all you need to do is take your desired inputs, cast them to a date stored in @date, and you can use the first example from that post without any changes. Using your code as-is, it only takes one more line of casting and then the first solution:
If you need to do this from year and month (assuming both are integers) you could create a function as so:
Example on SQL Fiddle
This would be a good solution.