Getting recent 100 Records with filter on date range

  • Hello,

    We have one complex procedure which returns top 100 recent records ,it was taking too much time because of data, so we have decided to filter it on date range for getting the records of only last 1 month , but we need at least 100 records,if last one month doesn't have 100 records then we need to make the filter of last 2 month.

    Please note that multiple tables used in procedure and it contains lakhs of records.

    How this logic can be written in SQL server 2005 ?

  • If you're going back one month or 2 months to find 100 records, why do you even care about a date range?

    ;WITH Tally ([Date]) AS (

    SELECT TOP 1000 DATEADD(day, ROW_NUMBER() OVER (ORDER BY (SELECT NULL))/3, '2012-02-28')

    FROM sys.all_columns a CROSS JOIN sys.all_columns b)

    SELECT [Date]

    FROM (

    SELECT [Date], n=ROW_NUMBER() OVER (ORDER BY [Date] DESC)

    FROM Tally) n

    WHERE n <= 100


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply