MS SQL Date Only Without Time

后端 未结 12 1537
有刺的猬
有刺的猬 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:29

    If you're using SQL Server 2008 it has this built in now, see this in books online

    CAST(GETDATE() AS date)

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

    Careful here, if you use anything a long the lines of WHERE CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam it will force a scan on the table and no indexes will be used for that portion.

    A much cleaner way of doing this is defining a calculated column

    create table #t (
        d datetime, 
    
        d2 as 
            cast (datepart(year,d) as varchar(4)) + '-' +
            right('0' + cast (datepart(month,d) as varchar(2)),2) + '-' + 
            right('0' + cast (datepart(day,d) as varchar(2)),2) 
    ) 
    -- notice a lot of care need to be taken to ensure the format is comparable. (zero padding)
    
    insert #t 
    values (getdate())
    
    create index idx on #t(d2)
    
    select d2, count(d2) from #t 
    where d2 between '2008-01-01' and '2009-01-22'
    group by d2
    -- index seek is used
    

    This way you can directly check the d2 column and an index will be used and you dont have to muck around with conversions.

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

    Alternatively you could use

    declare @d datetimeselect
    @d =  '2008-12-1 14:30:12'
    where tstamp 
      BETWEEN dateadd(dd, datediff(dd, 0, @d)+0, 0) 
      AND dateadd(dd, datediff(dd, 0, @d)+1, 0)
    
    0 讨论(0)
  • 2020-12-13 02:32

    FWIW, I've been doing the same thing as you for years

    CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam 
    

    Seems to me like this is one of the better ways to strip off time in terms of flexibility, speed and readabily. (sorry). Some UDF functions as suggested can be useful, but UDFs can be slow with larger result sets.

    0 讨论(0)
  • 2020-12-13 02:33
    DATEADD(d, 0, DATEDIFF(d, 0, [tstamp]))
    

    Edit: While this will remove the time portion of your datetime, it will also make the condition non SARGable. If that's important for this query, an indexed view or a between clause is more appropriate.

    0 讨论(0)
  • 2020-12-13 02:34
    WHERE DATEDIFF(day, tstamp, @dateParam) = 0
    

    This should get you there if you don't care about time.

    This is to answer the meta question of comparing the dates of two values when you don't care about the time.

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