Getting Started with Adobe After Effects - Part 6: Motion Blur
A collection of quick technology learning tips from what people around you learn every day

Smart Date Ranges

Jun 15 2011 1:59AM by Robert Dennyson   

Find records which date falls somewhere inside the current week.

where dateadd( week, datediff( week, 0, TransDate ), 0 ) =
dateadd( week, datediff( week, 0, getdate() ), 0 )

Find records which date occurred last week.

where dateadd( week, datediff( week, 0, TransDate ), 0 ) =
dateadd( week, datediff( week, 0, getdate() ) - 1, 0 )

Returns the date for the beginning of the current week.

select dateadd( week, datediff( week, 0, getdate() ), 0 )

Returns the date for the beginning of last week.

select dateadd( week, datediff( week, 0, getdate() ) - 1, 0 )
Read More..   [69 clicks]

Published under: SQL Server Tips ·  ·  ·  · 


Robert Dennyson
11 · 14% · 4420
2
 
2
 
 
0
Incorrect
 
0
Interesting
 
0
Forgotten



Submit

5  Comments  

  • Good one..

    First 2 queries are non-sargable. i would like to write the first 2 queries in a different way.

    Find records which date falls somewhere inside the current week.

    where TransDate >=
    dateadd( week, datediff( week, 0, getdate() ), 0 )
    

    Find records which date occurred last week.

    where TransDate >= dateadd( week, datediff( week, 0, getdate() ) - 1, 0 ) and 
    Transdate  < dateadd( week, datediff( week, 0, getdate() ), 0 )
    

    I have an article on datetime.

    http://beyondrelational.com/blogs/community/archive/2010/09/30/top-10-questions-on-datetime-asked-in-forums.aspx

    commented on Jun 15 2011 2:48AM
    Ramireddy
    2 · 40% · 12972
  • I agree with Rami that the first two queries could be horrible on a large table. In most cases this type of queries will result in table scans.

    commented on Jun 15 2011 4:54AM
    Jacob Sebastian
    1 · 100% · 32220
  • Indeed, don't promote functions on columns in where clauses. Use foldable expressions in stead as RamiReddy D showed.

    commented on Jun 15 2011 5:43AM
    Johan Bijnens
    1526 · 0% · 13
  • Agreed. The last two tips demonstrated are really cool. Many times we need to do calculations to find start and end date of a given period (week, month etc) and the logic demonstrated is worth noticing. It goes bad only when applied on a column.

    commented on Jun 15 2011 6:57AM
    JacobSebastian
    47 · 4% · 1215

Your Comment


Sign Up or Login to post a comment.

"Smart Date Ranges" rated 5 out of 5 by 2 readers
Smart Date Ranges , 5.0 out of 5 based on 2 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]