Get today’s or yesterday’s record with T-SQL


You can use DATEADD and DATEDIFF functions to get the start and end time of a particular day. You can compare your datetime column value with the start and end time and retrieve all records within the range.

Here is the code snippet:


 
 SELECT DATEADD(day, DATEDIFF(day,0,GETDATE())-1,0) as StartOfYesterday   
 SELECT DATEADD(day, DATEDIFF(day,0,GETDATE()),0) as StartOftheday  
SELECT DATEADD(day, DATEDIFF(day,0,GETDATE())+1,0) as StartOfNextday  
 
--Yesterday’s data 
 
…WHERE mydate >=DATEADD(day, DATEDIFF(day,0,GETDATE())-1,0) 
AND mydate < DATEADD(day, DATEDIFF(day,0,GETDATE()),0) 
 
--*****Today’s data 
…WHERE mydate >=DATEADD(day, DATEDIFF(day,0,GETDATE()),0) 
AND mydate < DATEADD(day, DATEDIFF(day,0,GETDATE())+1,0)

--Or
…WHERE mydate >=floor(cast(getdate() as float))
AND mydate < ceiling (cast(getdate() as float))

--*******
 

 
Advertisements

3 Comments on “Get today’s or yesterday’s record with T-SQL”

  1. ML says:

    So what is it for 3 days ago?

  2. Jrose says:

    Thank you. In 2015 you are still helping people find simple answers to hard to find solutions.

    Have no idea why it is so difficult to find today in sql server, but your answer is the only one among dozens found that actually works..


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s