MS SQL Date Only Without Time

后端 未结 12 1536
有刺的猬
有刺的猬 2020-12-13 02:02

Question

Hello All,

I\'ve had some confusion for quite some time with essentially flooring a DateTime SQL type using T-SQL. Essentially, I want to take a

相关标签:
12条回答
  • 2020-12-13 02:21

    CONVERT(date, GETDATE()) and CONVERT(time, GETDATE()) works in SQL Server 2008. I'm uncertain about 2005.

    0 讨论(0)
  • 2020-12-13 02:21

    Here's a query that will return all results within a range of days.

    DECLARE @startDate DATETIME
    DECLARE @endDate DATETIME
    
    SET @startDate = DATEADD(day, -30, GETDATE())
    SET @endDate = GETDATE()
    
    SELECT *
    FROM table
    WHERE dateColumn >= DATEADD(day, DATEDIFF(day, 0, @startDate), 0)
      AND dateColumn <  DATEADD(day, 1, DATEDIFF(day, 0, @endDate))
    
    0 讨论(0)
  • 2020-12-13 02:22

    The Date functions posted by others are the most correct way to handle this.

    However, it's funny you mention the term "floor", because there's a little hack that will run somewhat faster:

    CAST(FLOOR(CAST(@dateParam AS float)) AS DateTime)
    
    0 讨论(0)
  • that is very bad for performance, take a look at Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code

    functions on the left side of the operator are bad

    here is what you need to do

    declare @d datetime
    select @d =  '2008-12-1 14:30:12'
    
    where tstamp >= dateadd(dd, datediff(dd, 0, @d)+0, 0)
    and tstamp < dateadd(dd, datediff(dd, 0, @d)+1, 0)
    

    Run this to see what it does

    select dateadd(dd, datediff(dd, 0, getdate())+1, 0)
    select dateadd(dd, datediff(dd, 0, getdate())+0, 0)
    
    0 讨论(0)
  • 2020-12-13 02:27

    How about this?

    SELECT DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
    
    0 讨论(0)
  • 2020-12-13 02:28

    Yes, T-SQL can feel extremely primitive at times, and it is things like these that often times push me to doing a lot of my logic in my language of choice (such as C#).

    However, when you absolutely need to do some of these things in SQL for performance reasons, then your best bet is to create functions to house these "algorithms."

    Take a look at this article. He offers up quite a few handy SQL functions along these lines that I think will help you.

    http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx

    0 讨论(0)
提交回复
热议问题