Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL Date Only Without Time

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 DateTime value of say 2008-12-1 14:30:12 and make it 2008-12-1 00:00:00. Alot of the queries we run for reports use a date value in the WHERE clause, but I either have a start and end date value of a day and use a BETWEEN, or I find some other method.

Currently I'm using the following: WHERE CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam

However, this seems kinda clunky. I was hoping there would be something more simple like CAST([tstamp] AS DATE)

Some places online recommend using DATEPART() function, but then I end up with something like this:

  WHERE DATEPART(year, [tstamp]) = DATEPART(year, @dateParam) AND DATEPART(month, [tstamp]) = DATEPART(month, @dateParam) AND DATEPART(day, [tstamp]) = DATEPART(day, @dateParam)  

Maybe I'm being overly concerned with something small and if so please let me know. I just want to make sure the stuff I'm writing is as efficient as possible. I want to eliminate any weak links.

Any suggestions?

Thanks,
C

Solution

Thanks everyone for the great feedback. A lot of useful information. I'm going to change around our functions to eliminate the function on the left hand side of the operator. Although most of our date columns don't use indexes, it is probably still a better practice.

like image 387
regex Avatar asked Jan 21 '09 21:01

regex


People also ask

How can insert date without time in SQL Server?

Use Date Data type to create a Date column/variable without any time information. The time defaults to 00:00:00 and sql server will not store it in the Database. Hence it is very efficient way to store date, when there is no need to store time.

How do I convert datetime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.


2 Answers

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

CAST(GETDATE() AS date)

like image 186
JoshBerke Avatar answered Sep 18 '22 10:09

JoshBerke


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) 
like image 22
SQLMenace Avatar answered Sep 18 '22 10:09

SQLMenace