SQL Solutions for Finding the Last Day of a Month
Calculating the last day of a month is a frequent requirement in SQL database management. While DATEADD
can be used if you already have the first day of the month, a more versatile method is needed for arbitrary dates.
SQL Server 2012 introduced the EOMONTH
function, providing a straightforward solution. Its syntax is simple:
<code class="language-sql">EOMONTH(start_date [, month_to_add])</code>
start_date
is the input date. The optional month_to_add
parameter allows you to specify an offset (e.g., 1 for the last day of the next month).
To find the last day of the month for a given date, use:
<code class="language-sql">SELECT EOMONTH(@YourDate)</code>
Replace @YourDate
with your date variable. This directly returns the last day of the month containing that date.
The above is the detailed content of How Can I Efficiently Retrieve the Last Day of a Month in SQL?. For more information, please follow other related articles on the PHP Chinese website!