Not getting actual minutes in SQL DateDiff - sql

I searched in different places and found below queries. I am using the following queries to get the actual minutes difference in SQL. The dates I provide are the same day. I need difference in minutes only but SQL is returning 35 instead of 5 minutes in the first query. And the second query return milliseconds.
SELECT DATEDIFF(MINUTE,GETDATE(), CONVERT(datetime,'2016-08-11 16:04:24'))%3600/60 AS MinuteDiff
SELECT datediff(minute,GETDATE(), CONVERT(datetime,'2016-08-11 16:04:24')) as MinutesDiff
What is missing. Please help.
I need to put a condition that if time is less than 20 minutes then
do this
else
do this
Updated:
The issue occurs when i use GetDate(). When I use a fix date it works fine

You need to place the GETDATE() after your datetime value, other wise in your case you will get the minutes in negative value.
SELECT DATEDIFF(MINUTE,CONVERT(datetime,'2016-08-11 16:04:24'), GETDATE()) AS MinuteDiff
The current GETDATE() is 2016-08-11 17:05:39.053, so it returns 61.
Then based on the value, using IF ... ELSE ... you can do your expected operation:
IF DATEDIFF(MINUTE,CONVERT(datetime,'2016-08-11 16:04:24'), GETDATE()) < 20
PRINT 'With in 20 mins'
ELSE
PRINT 'More than 20 mins'

Here is a working example of what your after...although you probably need to switch out the date components as appropriate for your usage.
select
case
when
(SELECT datediff(minute,GETDATE(), CONVERT(datetime,'2016-08-11 06:00:00'))) < 20 then
(select 'do this')
else
(select 'do something else')
end as answer

If you want minute span between two datetime, then your second one is enough.
SELECT datediff(n, CONVERT(datetime,'2016-08-11 16:04:24'),GETDATE()) as MinutesDiff
you can use CASE for your further
select
case when
datediff(n, CONVERT(datetime,'2016-08-11 16:04:24'),GETDATE()) < 20 then
`your code`
else
`your else code`
end minte

Hey sorry for the initial poor explanation.
I use something like the following frequently this will return a INT and decide if it's then you can do the logic on it, equal to, not equal less than greater than etc.
If it is true it will return a 1 or it is false a 0. You can get it to return columns or set it to a string.
Hope it helps
select
Case
When DateDiff(minute,[column],Getdate()) > 20 then 1 else 0
end as [alias]

Related

MSSQL case statement - If the time is midnight then false, else true

I am looking to build a case statement that follows the logic below:
If the time of the date provided is midnight(00:00:00) then false(0), else true(1)
I am looking to present this in a view that lists a number of orders sent down to schedule delivery, where midnight is our default time (and since deliveries do not happen at midnight, this would mean it has not been scheduled yet, setting it to 0/false. This will be used as a condition to show either a red cross or green tick on a web interface.)
Any help is greatly appreciated.
Thanks in advance.
How about
SELECT CASE WHEN CAST([my-datetime] AS TIME) = '00:00:00.0000000' THEN 0 ELSE 1 END
FROM [my-table];
SELECT case WHEN CONVERT(nvarchar(10), myDate, 108)='00:00:00' then 0 else 1 END
statement FROM [my-table];
THIS SHOULD WORK
DECLARE #TBL TABLE (midnight DATETIME)
INSERT INTO #TBL VALUES
('2012-06-18T10:34:09'),('2018-09-25T10:54:31'),('2018-09-25T00:00:00'),
('2018-09-25T12:07:09'),('2017-05-06T00:00:00'),('2016-08-19T08:11:35')
SELECT
midnight,
CAST(midnight AS TIME),
CASE WHEN CAST(midnight AS TIME)='00:00:00' THEN 0 ELSE 1 END AS 'midnight_Col'
FROM #TBL

T-SQL: select data which datediff between dates exceed maximum unit

I have a table with two DateTime columns, start & end
I have a stored procedure which has a line like
select
...
...
where
datediff(second, start, end) > xxx`
I know for unit = second, the maximum difference between start and end is around 68 years.
Currently there are some false legacy data, which the difference between start and end is over 68 years, and when it came across this stored procedure, it will produce overflow error.
What I am trying to do is to write another script to select all such false data so that we can patch them, how can I do that? How can I select some records to fix the error which producing the error itself?
First, is it really necessary to do this to one second accuracy. After all:
where datediff(minute, start, end) > xxx / 60
or:
where datediff(hour, start, end) > xxx / (60 * 60)
but . . . if that won't do, you can try:
where dateadd(hour, xxx / (60 * 60),
dateadd(second, xxx % (60 * 60), start)
) > end
EDIT:
Actually, your problem is with the dates, not the xxx value. So, this should also work:
where dateadd(second, xxx, start) > end
This will work as long as xxx is an integer and start is not way too big (near the end of the range of whatever type it is).
Considering CASE statements resolve from left to right, you could try
Declare #YourTable table (id int,start datetime,[end] datetime)
Insert Into #YourTable values
(1,'1930-01-01','2016-09-25'), -- Greater than 2.14B seconds
(2,'2016-09-24','2016-09-25') -- Something more reasonable
Select *
from #YourTable
Where case when DateDiff(MINUTE,[start],[end]) > (2147483647/60) then 2147483647 else DateDiff(SECOND,[start],[end]) end > 100000
Returns (without an exception)
id start end
1 1930-01-01 00:00:00.000 2016-09-25 00:00:00.000
EDIT
I should add the trap of minutes allows for 4,080 years vs 68. Also, the default value of 2147483647 could be a more reasonable number or even 0 indicating suspect data.

SQL Server query to get next nearest date from recurring events

This is my scenario. I have a table with FirstMaintenanceEventDate and some data repeating after certain days from FirstMaintenanceEventDate. What I need to find out through a SQL Server query is to get the nearest date of each row among them.
Ex: there is a data row FirstMaintenanceEventDate is last month and it will repeat after 40 days which is next month. Likewise there are a lot of events here. Some of them have FirstMaintenanceEventDate in the future. Out of all these items I need to get the nearest date for each row.
I could get the nearest date without considering repeating process.
This is my query
SELECT TOP 1 *
FROM FIS_MaintenanceEventInstance
WHERE VehicleName = '600-GUR'
AND FirstMaintenanceEventDate >= GETDATE()
ORDER BY FirstMaintenanceEventDate ASC
Need to update it to consider repeat events as I describe above. Probably something like this but this isn't correct.
SELECT TOP 1 *
FROM FIS_MaintenanceEventInstance
WHERE
VehicleName = '600-GUR'
AND FirstMaintenanceEventDate >= GETDATE()
AND CASE
WHEN FirstMaintenanceEventDate < GETDATE()
THEN (Getdate() + RecurringDays)
END
ORDER BY FirstMaintenanceEventDate ASC
Any suggestion would be appreciated.
NOTE: If you need more information please let me now.
EDITED
I have tried follow query as Jatin Patel suggested in his answer below.
SELECT TOP 1 *,
CASE WHEN FirstMaintenanceEventDate < GETDATE() THEN DateAdd(day,RecurringDays,FirstMaintenanceEventDate)
ELSE FirstMaintenanceEventDate END AS MaintenanceEventDate
FROM FIS_MaintenanceEventInstance
WHERE VehicleName ='600-GUR'
ORDER BY MaintenanceEventDate ASC
This is not working as expected. After calculate the repeat date (here it's MaintenanceEventDate) also should consider when get the nearest date. According to this query it is calculate repeated date (MaintenanceEventDate) if it is in past and return it without check with other dates in the table.
Try this,
SELECT TOP 1 *,
CASE WHEN FirstMaintenanceEventDate < GETDATE() THEN (Getdate()+RecurringDays) ELSE FirstMaintenanceEventDate END AS MaintenanceEventDate
FROM FIS_MaintenanceEventInstance
WHERE VehicleName ='600-GUR'
ORDER BY MaintenanceEventDate ASC

SQL Select within a range of seconds

I have the table below
2012-05-24 19:00:00.000
2012-07-27 15:51:18.750
2012-07-30 09:40:25.333
2012-07-30 14:25:27.563
2012-07-27 15:51:18.750
2012-07-30 09:40:25.333
2012-07-30 14:25:27.563
2012-05-12 09:23:16.850
2012-05-12 18:00:00.000
I am trying to do a range select, so for example
SELECT * FROM RUN WHERE RUN_DATETIME = '14:25:29.563'
This is a very simple select, but my problem is that the date I am searching code be up too 30 seconds out from what is in the table above, so I need to be able to do the same as above but with a 30 second window and I am not sure what the best way to do this is.
This select is not based on another row, just the rows RUN_DATE within the window.
I am using SQL server 2008 R2
SELECT * FROM RUN
WHERE RUN_DATETIME < DATEDADD(s, '14:25:29.563', 30) AND
RUN_DATETIME > DATEDADD(s, '14:25:29.563', -30)
More complicated looking than podiluska's answer, but this works with indexes by pre-calculating the range.
SELECT *
FROM RUN
WHERE ABS(DATEDIFF(s, RUN_DATETIME , '14:25:29.563' ))< 30
SELECT
*
FROM
RUN
WHERE
RUN_DATETIME >= DATEADD(second, -30, '14:25:29.563')
AND RUN_DATETIME < DATEADD(second, 30, '14:25:29.563')
This is longer than the ABS(DATEDIFF()) version. It is, however, much faster when applied to indexed fields.
That is because the optimiser can easily see that you want all records within one sequential block. It can search for the start, then search for the end, and return everything between.
The ABS(DATEDIFF()) variation requires every row to be checked independantly, and makes no use of indexes or range seeks. It's a full scan of the whole table.
EDIT:
Also note that I use >= and <. This is standard practice for ranges of time.
For example val >= 0 AND val < 60 and val >= 60 AND val < 120 ensures that the value at val = 60 is only counted in one range of time.
I think RUN_DateTime column contains Date and comparison we are doing is with only Time here '14:25:29.563'. I agree with podiluska's answer. Just we would need to convert '14:25:29.563' to a date by taking out Day, month, year from RUN_DateTime column. We can do it by Date_Part function.

IF there is 24 hours between dates CASE statment

I am trying to create a case statment saying if 1 day or less has passed between my 2 date parameters then do this otherwise do this.....
Try this, however this only works in a query
case when datediff(hh,#Date1,#Date2) < 24 then.....
if it is in regular non query T-SQL just use an IF statement
IF datediff(hh,#Date1,#Date2) < 24
begin
-- stuff here
end
else
begin
-- stuff here
end
Explain "do this", because a CASE expression doesn't control flow.
SELECT CASE WHEN CAST(d1-d2 AS FLOAT) > 1 THEN '> 1 Day' ELSE '<= Day' END