Tuesday, September 24, 2013

SQL Trick KB: Algorithm - Last date of the month

This post was published at my beloved old blog "On the quest of a DBA's adventure......"

".... Hang on. How hard could it be? "

In a quiet afternoon a while ago, I was enjoying the challenge from a T-SQL quiz question. It asked how to get the last date of the month for a given date, say for reporting purpose. I thought: ".... Hang on. How hard could it be?". It successfully occupied me mentally for an hour.

The main deal is that the last day of a month is not necessary in a regular pattern. It could be 30, 31, ..... 28, or even 29. It all depends on which month and which year you are talking about. I was thinking to take the given date and disassemble it, took the month and make up the first day then subtract 1 day... too complex,really.

Inspired by Pinal Dave's blog post SQL SERVER – Query to Find First and Last Day of Current Month . Here is the code:

It returned a list of the error in different languages. If you are lucky, you now know what they mean. OK, it is not "world-savingly" great, but it may be a little step forward to the solution at least.

Here's a different approach to get last day of the month for a given date

No comments:

Post a Comment