Home >Database >Mysql Tutorial >How to Efficiently Retrieve Records from the Last Month in SQL Server?

How to Efficiently Retrieve Records from the Last Month in SQL Server?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 07:32:40587browse

How to Efficiently Retrieve Records from the Last Month in SQL Server?

Get Records from Last Month in SQL Server

To retrieve records from the last month, we need to use the date_created field in the member table. Here's a query that will accomplish this task:

WHERE date_created >= @startOfPreviousMonth AND date_created < @startOfCurrentMonth

To ensure that indices are used and incorrect data is excluded, we need to calculate the @startOfPreviousMonth and @startOfCurrentMonth variables as follows:

DECLARE @startOfCurrentMonth DATETIME
SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)

DECLARE @startOfPreviousMonth DATETIME
SET @startOfPreviousMonth = DATEADD(month, -1, @startOfCurrentMonth)

Finally, the modified query would look like this:

SELECT *
FROM Member
WHERE date_created >= @startOfPreviousMonth
AND date_created < @startOfCurrentMonth

This approach ensures optimal performance and data accuracy.

The above is the detailed content of How to Efficiently Retrieve Records from the Last Month in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn