|
Dates - Finding # Days In A Month
|
|
One of the most common question that people ask for the date functions in SQL Server is "how do I find the number of days in a given month". There is no direct method in SQL Server for finding this out, but we can play around a bit with the date functions of SQL Server and generate the value. Here is a simple algorithm for finding the number of days in a month.
Here is the T-SQL that will accomplish the above algorithm.
In the above algorithm, we used the current date function (called GETDATE())
and perform the algorithm on this function. The important functions that you need to note in this T-SQL
statement are:
Ok, let's use the function that we have learned above, to print out the number of days in each month for a given year. Here is the T-SQL block for the same.
The code for generating the table is very simple. We use a table variable to store the result and use a loop variable to iterate through each month. We then form a date variable of the form month/01/2003 and then apply our function on this variable. Finally we print out the contents of this table. Here is what the output of the above program will look like:
|
| Home |