How to get only date part while using dateadd() and getdate() - sql

I want to display records of last 4 months from current date.
I don't want to consider time
How can I get just date part from the below query?
where OrderDate >= DATEADD(month, -4, GETDATE())

If you're using SQL Server 2008, try converting GETDATE() to a DATE directly.
WHERE OrderDate >= DATEADD(month, -4, CONVERT(date, GETDATE()))
http://sqlfiddle.com/#!3/df444/2

Why not use the simple DATEDIFF function
where DATEDIFF(MM, OrderDate, GETDATE()) < 4

If you can't use the DATE type, there's the old way: convert the DATETIME value to CHAR, trim the hour components and then convert it back to DATETIME, so the hour components will be zeroed:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112), 112)
-- -----------------------
-- 2014-02-25 00:00:00.000
The important thing is to use the function over the scalar parameter (and not on the column) to allow the usage of existing indexes.

Related

Getdate() functionality returns partial day in select query

I have a query -
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00.
Try it like this:
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from getdate(): you can accomplish that with a conversion to date:
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
If you want to start from 8 in the morning, the best is to add again 8 hours to getdate.
declare #t datetime = dateadd(HH, 8, convert(datetime, convert(date, getdate())))
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -#t) AND Date <= #t;
NOTE: with the conversion convert(date, getdate()) you get a datatype date and you cannot add hours directly to it; you must re-convert it to datetime.
Sounds like you want to remove the time. Correct? If so then do the following.
SELECT * FROM TABLE WHERE Date >= (DATEADD (day, -7, -getdate()) AND Date DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))

How to get 00:00:00 in datetime, for First of Month?

I wrote a query to obtain First of month,
SELECT DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as First_Of_Month;
for which i do get the appropriate output, but my time stamp shows the current time.
Here's what I am doing in the query, hope i make sense.
using datepart i calculated the no. of days (int) between the 1st and today (27-1 =26)
Then using dateadd function, i added "-datepart" to get the first of the month.
This is just changing the date, what should i look at or read about in order to change the time. I am assuming that it would have something to do with 19000101
For SQL Server 2012 (thanks adrift and i-one)
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
SELECT DATEADD(DAY, 1, EOMONTH(#now, -1));
-- or
SELECT DATEFROMPARTS(YEAR(#now), MONTH(#now), 1);
For SQL Server 2008+
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
-- This shorthand works:
SELECT CONVERT(DATE, #now+1-DAY(#now));
-- But I prefer to be more explicit, instead of relying on
-- shorthand date math (which doesn't work in all scenarios):
SELECT CONVERT(DATE, DATEADD(DAY, 1-DAY(#now), #now));
For SQL Server 2005
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);
A caveat if you're using this SQL Server 2005 method: you need to be careful about using expressions involving DATEDIFF in queries. SQL Server can transpose the arguments and lead to horrible estimates - as seen here. It might actually be safer to take the slightly less efficient string approach:
SELECT CONVERT(DATETIME, CONVERT(CHAR(6), GETDATE(), 112) + '01');
SELECT convert(varchar(10),DATEADD(DAY, - (DATEPART(DAY,GETDATE())-1), GETDATE()),120)+' 00:00:00' as First_Of_Month;
Just the date
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
So for a month it is:
DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) AS FirstDatetimeOfMonthmm,
I think the easiest way is to cast the result to date:
SELECT cast(DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as date) as First_Of_Month
One alternative:
SELECT cast(
cast(datepart(yyyy, getdate()) as varchar)
+ '-'
+ cast(datepart(mm, getdate()) as varchar) + '-01 00:00:00'
as datetime)
Build up the date from year/month components, then tack on the 1st and midnight.
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) as First_Of_Month;
Try following code:
SELECT CAST(CAST(GETDATE() AS DATE) AS DATETIME) AS StartDateTime,
DATEADD(ms, -3, CAST(CONVERT(date, DATEADD (DAY,1,GETDATE())) AS varchar(10))) AS EndDateTime
Result:
StartDateTime
EndDateTime
2022-05-23 00:00:00.000
2022-05-23 23:59:59.997

Getting rows between date range is not working in SQL Server

In SQL Server 2008R2 fetching data between two dates is not working.
I am using the following code to get rows from the INVOICE table where the CREATED_DATE is between #startdate and #enddate, which are the parameters I am sending to the stored procedure.
Select *
from INVOICES INV
where CONVERT(Varchar(10), INV.CREATED_DATE, 105)
BETWEEN CONVERT(VARCHAR(10), #startdate, 105)
AND CONVERT(VARCHAR(10), #enddate, 105)
It is not working properly, driving me nuts..
What I am doing wrong?..
select * from
invoices inv
where inv.created_date >= dateadd(dd, 0, datediff(dd, 0, #startdate))
and inv.created_date < dateadd(dd, 1, datediff(dd, 0, #enddate))
First of all, do not convert your start/end and column's dates to varchar, and if you do so remember that 105 (returns dd-mm-yyyy) is not comparable, 112 (returns yyyymmdd) would be better (when you are interested in date part only). But what I've said it's better not to convert and just compare dates.
Added:
And little explanation: dateadd(dd, 0, datediff(dd, 0, #startdate)) - returns date part only of datetime, dateadd(dd, 1, datediff(dd, 0, #startdate)) - returns next day date part only.
Query returns all rows for your parameters inclusively (regardless of the hour).
Since you're on SQL Server 2008 R2, you could just convert everything to the DATE format:
SELECT *
FROM dbo.INVOICES INV
WHERE CAST(INV.CREATED_DATE AS DATE)
BETWEEN CAST(#startdate AS DATE) AND CAST(#enddate AS DATE)
Since you're using the DATE type, you're independent of any dateformat or language settings or any of those tricky features. SQL Server will just compare dates - as it should.
And of course: if you make your stored procedure parameters #startdate and #enddate to be of type DATE from the beginning, then you can save yourself those two CAST operations, too!
SELECT *
FROM dbo.INVOICES INV
WHERE CAST(INV.CREATED_DATE AS DATE) BETWEEN #startdate AND #enddate
(and if you made CREATED_DATE of type DATE - you could even forget about that last CAST in the statement, too!)
Default setting is yyyy-MM-dd
If you use 105 which means you're trying to parse date as format dmy, so before executing add below line at the top of your query.
SET DATEFORMAT DMY

TSQL SELECT previous date's records

I want to select all records from a table Log where the DateAndTime field values (of type datetime) are for the day before today, whatever day it is.
So if today is 2011-06-08, I want to select all rows where DateAndTime is greater than or equal to 2011-06-07 00:00:00 and also less than 2011-06-08 00:00:00.
I'm guessing the potential pitfall here would be it's behaviour on the 1st day of the month, as obviously a date like 2011-06-00 is invalid, and should be 2011-05-31.
For SQL Server 2008 you can use this.
select *
from [log]
where cast(DateAndTime as date) = cast(getdate()-1 as date)
Pre 2008 you can use this
select *
from [log]
where DateAndTime >= dateadd(d, datediff(d, 0, getdate())-1, 0) and
DateAndTime < dateadd(d, datediff(d, 0, getdate()), 0)
Related on DBA: Cast to date is sargable but is it a good idea?
SELECT * FROM Log
WHERE DateAndTime >= DATEADD(DAY,-1, CAST(GETDATE() AS DATE))
AND DateAndTime < CAST(CAST(GETDATE() AS DATE) AS DATETIME)
This example assumes SQL Server:
select *
from log
where convert(varchar(8), DateAndTime , 112) = convert(varchar(8), getdate()-1, 112)
Essentially, convert the date to yyyymmdd (the 112 parameter) and then check it is equal to yesterday's date (getdate()-1), also converted to yyyymmdd.
Assuming SQL Server
declare #today date
set #today = GETDATE()
select * from Log where DateAndTime between DATEADD(dd, -1, #today ) and #today
It should include conditional operator and not between .
Otherwise it includes today's records as well.
Declare #today date
Set #today = GETDATE()
Select YourcolumnNames from log
Where DateAndTime >= DATEADD(dd, -1, #today ) and DateAndTime < DATEADD(dd, -1, #today )
Moreover, you should mention the column name and * should be avoided in the select statement. This can improve the performance

checking for smalldatetime column equal to GetDate() - ignoring time

I have a column of smalldatetime type, date
I'd like to run a query that only retrieves rows:
where date = convert(smalldatetime,GetDate())
However, this is never finding matches as it is also comparing the times.
Ie: 01-01-2010 12:23:00 != 01-01-2010 12:25:00
How can I find matches on only the date portion?
One way which will utilize the index
where date >= dateadd(dd, datediff(dd, 0, getdate()), 0)
and date < dateadd(dd, datediff(dd, 0, getdate()), +1)
See also: How Does Between Work With Dates In SQL Server?
Try:
where datediff(dd, yourdate, GetDate()) = 0
Convert your DateTime values to Date values. That will store only the date portion for you to compare.
A list of available Date and Time datatypes in MSSQL is here.
You could try:
Where CAST(FLOOR(CAST([Date] AS FLOAT)) AS DATETIME) = CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
This would make both dates appear as:
2010-08-05 00:00:00.000
and thus only comparing the dates ignoring the times
found this:
CAST(CONVERT (CHAR(8), GETDATE(), 112) AS smalldatetime)
from here:
reference
this sql worked for me when I added a smalldatetime field to an existing table:
SELECT testing
FROM LTCCAssessment
WHERE (testing = CAST(CONVERT(CHAR(8), GETDATE(), 112) AS smalldatetime))
where cast(CONVERT(char(10),DATETIME_FIELD_1,101) as datetime)
= cast(CONVERT(char(10),DATETIME_FIELD_2,101) as datetime)