简体   繁体   中英

How can I modify this SQL query to exclude all results except from the previous two hours?

We're currently using SQL Express on SQL Server 2005 and want to set up an automated ftp file transfer every two hours to our client. We want to be able to send them bi-hourly uploads without duplicates throughout the day. Is this possible to do by modifying this existing query?

    Use Sweet
    select distinct d.AccountCode, f.ProcessedFileName, f.CallStartDateTime, f.PathToFile 
    from CSR_CallDetail d, CSR_FileListing f
    where d.CallId = f.CallId 
    and f.ProcessedFileName like '%mp3'
    and f.CallStartDateTime between convert(varchar(10),getdate()-1,101) and convert(varchar(10),getdate(),101)
    and d.AccountCode > '740000'
    and f.AccountCode > '740000'
    and not exists (select 1 from( select processedfilename from csr_filelisting) p 
                                 where f.compressedfilename = p.processedfilename)

Here's the updated query

    Use Sweet
    select distinct d.AccountCode, f.ProcessedFileName, f.CallStartDateTime, f.PathToFile 
    from CSR_CallDetail d, CSR_FileListing f
    where d.CallId = f.CallId 
    and f.ProcessedFileName like '%mp3'
    and DATEDiff(hh, f.callstartdatetime, GETDATE ()) <=2
    and d.AccountCode > '740000'
    and f.AccountCode > '740000'
    and not exists (select 1 from( select processedfilename from csr_filelisting) p where f.compressedfilename = p.processedfilename)

Let's say the query you posted returns desired result. If so, we need a date (and time) the records have been saved. All you need is to add condition:

AND DATEDIFF(hh, date_of_record, GETDATE()) <=2

I assume in your case it will be:

AND DATEDIFF(hh, f.CallStartDateTime , GETDATE()) <=2

You won't be able to rely on timestamps to get guaranteed exact sequential nonoverlapping sets of anything. You'll always be up against a race condition. What you should do is add a bit column somewhere that will mean you've already processed that row, and set it appropriately at the time of processing. Use transactions and isolation levels to ensure that no one is updating it while you're working on it (a brief moment, one hopes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM