Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query Help

Status
Not open for further replies.

SpeedStick

Technical User
May 24, 2007
37
0
0
US
All,

I need to write a query in SQL Server 2008 that will find all records that have an end date for next month and also all records for the previous months.

This query needs to be re-used in subsequent months.

Thank you,

Scott



 
Look at the DATEADD function. Also the MONTH and YEAR functions.

djj
The Lord is my shepherd (Psalm 23) - I need someone to lead me!
 
All:

Thanks for the suggested. I developed my own solution for myself.
Below is solution:

SELECT tblSubscriptionInformation.CompanyName, tblSubscriptionInformation.EndDate, tblSubscriptionInformation.Status
FROM tblSubscriptionInformation
WHERE ((Year([EndDate])*12+DatePart("m",[EndDate])<=Year(Date())*12+DatePart("m",Date())+1) AND ((tblSubscriptionInformation.Status)="Current"))
ORDER BY tblSubscriptionInformation.EndDate DESC;

Scott
 
Scott,

although your code will work, it has a potential issue with the fact that if field EndDate is a index of that table, it will not be used.

The following would give you the same results, and would allow the index to be used.

Code:
SELECT tblSubscriptionInformation.CompanyName
      ,tblSubscriptionInformation.EndDate
      ,tblSubscriptionInformation.Status
FROM tblSubscriptionInformation
WHERE EndDate < dateadd(m,2,convert(date,convert(varchar,(Year(getDate()))) +right('0'+convert(varchar,DatePart("m",getDate())),2) +'01',112))
  AND tblSubscriptionInformation.Status="Current"
ORDER BY tblSubscriptionInformation.EndDate DESC;

Regards

Frederico Fonseca
SysSoft Integrated Ltd

FAQ219-2884
FAQ181-2886
 
That seems to be quite a complicated expression to test the date against. Since DATEADD(mm,1+DATEDIFF(mm,0,getdate()),0) will give the first day of next month, how about just

Code:
SELECT tblSubscriptionInformation.CompanyName
      ,tblSubscriptionInformation.EndDate
      ,tblSubscriptionInformation.Status
FROM tblSubscriptionInformation
WHERE EndDate < [red]DATEADD(mm,1+DATEDIFF(mm,0,getdate()),0)[/red]
AND tblSubscriptionInformation.Status="Current"
ORDER BY tblSubscriptionInformation.EndDate DESC;

soi là, soi carré
 
Frederico,
Re-reading Scott's post, I see that what you say is right; thanks.

soi là, soi carré
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top