differences between dates in sql - sql-server

I have two columns namely enddate and startdate
I need to find all those records where
(enddate-startdate)>2 years
I tried using timediff(enddate,startdate)>2
But it returns an error saying : 'timediff' is not a recognized built-in function name
I am using sql server management studio, any help ?
My date format is 2007-04-16 00:00:00.000

Try to use DateDiff
DateDiff(year,enddate,startdate)

WHERE dateadd(year, -2, enddate) > startdate

I would use DATEDIFF. It should get you there at a macro level.
DECLARE #orderTracker TABLE (
orderDate DATE,
orderShipped DATE,
orderNum VARCHAR(6)
);
INSERT INTO #orderTracker
( orderDate, orderShipped, orderNum )
VALUES ('01/01/2012', '06/12/2013', '55YY7'),
('05/20/2006', '09/10/2008', 'sdlhf8'),
('06/02/2011', '10/12/2012', '34JJU'),
('11/25/2009', '06/12/2013', '553iSS'),
('06/15/2008', '12/12/2011', '5F09U7'),
('02/06/2013', '08/12/2013', '55YY7');
SELECT * FROM #orderTracker;
SELECT *
FROM #orderTracker
WHERE DATEDIFF(YEAR, orderDate, orderShipped) >= 2;

Use DateDiff
WHERE DATEDIFF(year, startdate, enddate) > 2
EDIT: Duplicated, I had not seen the answer of Jayesh Goyani, sorry!

From discussion in comments, your best bet is to establish a threshold date using the start datetime and dateAdd function. This will give you all records where the end time is after the datetime at the same time of day, on the same calendar date (month, day of month), two years after the start date.
Where endDate > dateadd(year, 2, startDate)

Please use 'Year' in DateDiff
DATEDIFF(year, startdate, enddate) > 2
For more information please check below link.
http://msdn.microsoft.com/en-us/library/ms189794.aspx

This should return the number of years:
DATEDIFF(year,'2008-06-05','2008-08-05')

DATEDIFF does not work correctly for this situation as of the time of me writing this. Actually, it doesn't work correctly at all and no one should use it.
Example being;
DATEDIFF(YEAR, '2016-08-28', '2017-04-28')
Returns 1, although it has not been a year. It simply subtracts the years and doesn't take into account the months or days.
Use the DATEADD method instead, as others have suggested.

Related

How to get date before 3 months from a particular date, say current date in SQL?

How can we deduce the date falling exactly 3 months prior to the current date in SQL Server?
use dateadd
select convert(date, dateadd(month,-3,getdate()))
output
16/07/2018 00:00:00
Use DATEADD() function
SELECT DATEADD(M, -3,GETDATE()) AS WithTime,
CAST(DATEADD(M, -3, GETDATE()) AS DATE) AS WithoutTime
If you are working on newest versions of SQL Server (2012+) I would recommand to use TRY_CONVERT() or TRY_CAST() functions.

In SSMS how can I use the DATEADD function to grab all values between '2018-09-01 00:00:00.000' and '2018-09-01 023:59:00.000'

I am using SQL Server Management Studio 2014 and trying to write a query to grab all values that have the next days date for orders I do not want to hard code the between clause for the date and want to use DateAdd or a similar function so it works consistently without changing the syntax. Example of hard coded query is below.
SELECT OrderId
FROM [XXXX].[dbo].[INBOUNDORDHEADER]
between '2018-09-01 00:00:00.000' and '2018-09-01 023:59:00.000'
What is the best way to write the syntax for this utilizing the DATEADD or similar function?
Is there a way I can not discriminate against the time of the values retrieved? For example just pull everything with 2018-09-01 and not exclude records based on their time format
Can I use AddDate with between to accomplish this?
Making the WHERE clause SARGABLE so that it can benefit from indexes can greatly improve performance. It is best not to fiddle about with trying to get the "last" time in a day, just use a half-open interval:
declare #Today as DateTime = Cast( GetDate() ); -- Strip the time-of-day.
select OrderId
from [XXXX].[dbo].[INBOUNDORDHEADER]
where DateAdd( day, 1, #Today ) <= OrderDate and OrderDate < DateAdd( day, 2, #Today );
Not super elegant, but you can use a cast to DATE to strip the time:
SELECT OrderId
FROM [XXXX].[dbo].[INBOUNDORDHEADER]
BETWEEN DATEADD(day, 1, CAST(GETDATE() As DATE)) AND DATEADD(day, 2, CAST(GETDATE() As DATE))
This will give you the date range between midnight tomorrow and midnight the day after. Using your example and today's date, it'll be BETWEEN '2018-09-01 00:00:00' AND '2018-09-02 00:00:00'
I think the 'cleanest' way is to use DATEFROMPARTS and DATEPART methods:
SELECT OrderId
FROM [XXXX].[dbo].[INBOUNDORDHEADER]
WHERE DATEFROMPARTS(
DATEPART(YEAR, OrderDate),
DATEPART(MONTH, OrderDate),
DATEPART(DAY, OrderDate)) = '2018-09-01'
Edit: This is not good for performance. See HABO's answer for the optimal way to do this.

How to retrieve all rows with a date in this and the next week? SQL Server

I have a Tasks table that contains Date, Description and WorkerID columns. I want to write a stored procedure that selects all tasks from this week and the following week. Can someone help me get to a solution please? I am not so good at this.
If indexing (performance) isn't a concern then it's a simple expression if your week coincides with the SQL Server setup:
where datediff(week, getdate(), [Date]) between 0 and 1
The snippet below is another option that works with both dates and datetimes. It's possible to adapt it to work with any ##datefirst setting but I'm just going to assume that the setting matches with the start of week you're looking to report on.
where
[Date] >= dateadd(day, 1 - datepart(weekday, getdate()), cast(getdate() as date))
and [Date] < dateadd(day, 15 - datepart(weekday, getdate()), cast(getdate() as date))
The following should give you what you want (assuming Monday is the first day of the week, and that the DBMS is SQL Server):-
select *
from Tasks
where [Date]
between
dateadd(dd,-(datepart(dw,[Date])-2),[Date]) --Monday of this week
and
dateadd(dd,13,dateadd(dd,-(datepart(dw,[Date])-2),[Date])) --Sunday of next week

How to add days to the current date?

I am trying to add days to the current date and it's working fine but when I add 360 days to the current date it gives me wrong value.
eg: Current Date is 11/04/2014
And I am adding 360 Days to it, it should give me 11/04/2015, but it is showing the same date 11/04/2014. the year is not changing.
Here is my code:
select dateadd(dd,360,getdate())
Just do-
Select (Getdate()+360) As MyDate
There is no need to use dateadd function for adding or subtracting days from a given date. For adding years, months, hours you need the dateadd function.
select dateadd(dd,360,getdate()) will give you correct date as shown below:
2017-09-30 15:40:37.260
I just ran the query and checked:
Dateadd(datepart,number,date)
You should use it like this:
select DATEADD(day,360,getdate())
Then you will find the same date but different year.
From the SQL Server 2017 official documentation:
SELECT DATEADD(day, 360, GETDATE());
If you would like to remove the time part of the GETDATE function, you can do:
SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
can try this
select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result
Two or three ways (depends what you want), say we are at Current Date is
(in tsql code) -
DECLARE #myCurrentDate datetime = '11Apr2014 10:02:25 AM'
(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)
SELECT #myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.
SELECT DateADD(DAY, 365, #myCurrentDate) or DateADD(dd, 365, #myCurrentDate)
will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE #myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).
So what I think you meant was
SELECT DateADD(year, 1, #myCurrentDate)
which gives 2015-04-11 10:02:25.000.
or better yet
SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, #myCurrentDate), 0))
which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?
This will give total number of days including today in the current month.
select day(getDate())
Add Days in Date in SQL
DECLARE #NEWDOB DATE=null
SET #NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)
SELECT DateAdd(5,day(getdate()) this is for adding 5 days to current days.
for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query

Select Records for which the date field is spent a year

I have a table with columns
TypeExame, DateExame
How can I select all records with (Now-DateExame) > = 365 days?
select *
from MyTable
where datediff (day, DateExame, getdate()) >= 365
See DATEDIFF and GETDATE for further details.
If you have an index on DateExame, putting the condition like this will enable its usage:
SELECT *
FROM atable
WHERE DateExame <= DATEADD(DAY, -365, CAST(GETDATE() AS date))
;
The above references the date data type, which means you'd need at least SQL Server 2008 to run that. To make it work in earlier versions, you could rewrite the condition like this:
WHERE DateExame <= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 365, 0)
Basically, the modified version uses the DATEADD/DATEDIFF method of truncating a datetime value with a minor tweak to also subtract 365 days along the way.
However, if all your DateExame values are dates without the time part, this simpler version should work just as well:
WHERE DateExame <= DATEADD(DAY, -365, GETDATE())
That is, removal of GETDATE()'s result's time part would be perfectly unnecessary.
Try this one :
select *
from MyTable
where datediff (day, DateExame, getdate()) >= 365
By Using Datediff function you can subtract two dates . you can pass first argument as minute , day , month , year etc .

Resources