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

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

Related

SQL Query to set flag based on Start Date and Previous Close Date

I've tried searching this up, but nothing really matched with what I was looking for, so any help is appreciated!
And what I want is to have an Expression or flag which should return true if the number of days between previous closed date and current Start date is less than 10 for the TASK ID.
For Example The above table should looks like
Note:
I only have read-only access, so 'update queries' and 'create new table' queries are not applicable for my case.
In SQL Server, you can use lag():
select t.*,
(case when lag(close_date) over (partition by task_id) < dateadd(day, -10, close_date)
then 1 else 0
end) as flag
from t;

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.

Not getting actual minutes in SQL DateDiff

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]

Converting a time excel formula to t-sql

So I'm new to SQL (I believe it's T-SQL) and I'm trying to convert a function I used in Excel to SQL.
L2 becomes Column 1
G2 becomes Column 2
=(INT(L2)-INT(G2))*("17:00"-"08:45")+MEDIAN(MOD(L2,1),"17:00","08:45")-MEDIAN(MOD(G2,1),"17:00","08:45")
What this does is calculate the business hours worked between 8:45AM and 05:00PM.
If work goes from 4:00PM to 9:00AM the next day, the result should be 01:15:00.
If it goes over several days (4:00PM on the 1st to 9:00AM on the 4th) it should be 17:45:00.
I'd prefer not to have a separate function because I don't know how to use them as I'm quite new to this - I'd prefer to have it as something I can write within the SELECT * , <code here here> FROM db.name section.
Thanks in advance
I know you said you don't want this in a function, but they really aren't hard to use and the logic you require for this is too complex in SQL Server to be sensibly contained inline (Though it can be, if you really want to be that guy).
This function has no error handling if any of your parameters are not suitable, though I will leave that up to you as a learning exercise on NULL values, process flows and fully thinking through all the possibilities that you may need to deal with:
-- This bit creates your function. You can rename the function from fnWorkingDays to anything you want, though try to keep your naming conventions sensible:
create function fnWorkingDays(#Start datetime
,#End datetime
)
returns decimal(10,2)
as
begin
-- Declare the start and end times of your working day:
declare #WorkingStart time = '08:45:00.000'
declare #WorkingEnd time = '17:00:00.000'
-- Work out the number of minutes outside the working day in 24 Hour Notation:
declare #OvernightMinutes int = datediff(minute -- Work out the difference in minutes,
,cast(#workingend as datetime) -- between the end of the working day (CASTing a TIME as DATETIME gives you 1900-01-01 17:00:00)
,dateadd(d,1,cast(#WorkingStart as datetime)) -- and the start of the next working day (CAST the TIME value as DATETIME [1900-01-01 08:45:00] and then add a day to it [1900-01-02 08:45:00])
)
-- There is no need to retain the minutes that fall outside your Working Day, to if the very start or very end of your given period fall outside your Working Day, discard those minutes:
declare #TrueStart datetime = (select case when cast(#Start as time) < #WorkingStart
then dateadd(d,datediff(d,0,#Start),0) + cast(#WorkingStart as datetime)
else #Start
end
)
declare #TrueEnd datetime = (select case when cast(#End as time) > #WorkingEnd
then dateadd(d,datediff(d,0,#End),0) + cast(#WorkingEnd as datetime)
else #End
end
)
-- You can now calculate the number of minutes in your true working period, and then subtract the total overnight periods in minutes to get your final value.
-- So firstly, if your Working Period is not long enough to stretch over two days, there is not need to do any more than calculate the difference between the True Start and End:
return (select case when datediff(minute,#Start,#End) < #OvernightMinutes
then datediff(minute,#TrueStart,#TrueEnd)
-- If you do need to calculate over more than one day, calculate the total minutes between your True Start and End, then subtract the number of Overnight Minutes multiplied by the number of nights.
-- This works because DATEDIFF calculated the number of boundaries crossed, so when using DAYS, it actually counts the number of midnights between your two dates:
else (datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes))/1440.
-- If you want to return your value in a slightly different format, you could use variations of these two, though you will need to change the RETURNS DECIMAL(10,2) at the top to RETURNS NVARCHAR(25) if you use the last one:
-- else datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes)
-- else cast((datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes))/60 as nvarchar(5)) + ' Hours ' + cast((datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes))%60 as nvarchar(5)) + ' Minutes'
end
)
end
go
And this is how you call the function:
select dbo.fnWorkingDays('2016-09-04 12:00:00.000', '2016-09-06 12:10:00.000') as WorkingDays
You can replace the two DATETIME values about with the appropriate column names to get your desired result inline:
select dbo.fnWorkingDays(Dates.StartDate, Dates.EndDate) as WorkingDays
from (select '2016-09-04 12:00:00.000' as StartDate
,'2016-09-06 12:10:00.000' as EndDate
) as Dates

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