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
Release: 2025-01-03 07:32:40
Original
615 people have browsed it

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
Copy after login

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)
Copy after login

Finally, the modified query would look like this:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template