SQL Server code to add time to date time if after certain time - sql

I am NEW to SQL Server coding, so please be kind.
I am trying to look at a column and if the time is after 11am then I need to add 1 day to the date and display the new date. If prior to 11am, it doesn't need to add a day, but instead just show the date itself.
As you can see in the picture the "FDP Date" is adding a day no matter what time it shows (IE:lines 3 & 4). As if the time is before 11am it show not add any time.
Please let me know if you can help.
Thank you in advance,
Brian
Code:
SELECT
[ReceiptDate],
[DeptRcptDate],
CASE
WHEN DeptRcptDate >= '11:00:00'
THEN DATEADD (DAY, 1, DeptRcptDate)
WHEN DeptRcptDate < '11:00:00'
THEN (DeptRcptDate)
ELSE 'Unknown'
END AS "FDP Date",
[OutcomeLtrDate],
CASE
WHEN OutcomeLtrDate >= '16:00:00'
THEN (OutcomeLtrDate) + 1
WHEN OutcomeLtrDate < '16:00:00'
THEN (OutcomeLtrDate)
ELSE 'Unknown'
END AS "LDP Date"
Picture of (same) code.

You can use a CASE statement with DATEPART
declare #date datetime = '20160801 11:01:00'
select
case
when datepart(hour,#date) >= 11
then dateadd(day,1,#date)
else #date
end

'11:00:00' is 11am of the zero date (January 1, 1753). Obviously all your dates are greater than that.
If you want to compare times only, cast to time first:
case when cast(DeptRcptDate as time(0)) >= '11:00:00' then dateadd(d, 1, DeptRcptDate)

You're checking a datetime against a string contaiing a time. I'm not surprised it's giving unexpected results.
Get the time portion of your datetime with datepart(), and compare that.
https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-2017

Related

Why is '=' operator not working on comparing Datetime?

I am trying to fetch records only of the current day. I have used the = operator to compare the date but it is not working, if I subtract 1 from the current date and then use >= operator then it works.
I am putting both queries here.
This code works:
1 = (
CASE WHEN ISNULL(DO.CREATEDON, '') >= GETDATE()-1
THEN 1
END
This code doesn't work:
1 = (
CASE WHEN ISNULL(DO.CREATEDON, '') = GETDATE()
THEN 1
END
Why is the latter code not working?
GETDATE() returns a datetime, so (for me), right now, using GETDATE() returns something like 2021-01-19T09:43:27.123. It's therefore very unlikely the value in your column CREATEDON is going to be the same exact time that GETDATE() returns, accurate to the nearest 1/300 of a second.
If your column CREATEDON is a date and time value, use inclusive date ranges:
WHERE DO.CREATEDON >= CONVERT(date,GETDATE())
AND DO.CREATEDON < CONVERT(date,DATEADD(DAY, 1, GETDATE())
If CREATEDON is a date, then just CONVERT the value of GETDATE() to a date:
WHERE DO.CREATEDON = CONVERT(date,GETDATE())
Note that there's no need for the ISNULL, as is the value of NULL it is by definition not the value of GETDATE(). Also, converting'' to a date and time value is a little odd; but it would convert to 1900-01-01, which again, is not today. Adding an ISNULL on DO.CREATEDON in the WHERE will only harm the performance; don't do it.

SQL Server compare time in IF Condition

I am trying to compare starttime and GETDATE() time by taking there time part but in SQL Server if condition is not satisfying even though it should do by seeing .
IF (CONVERT(VARCHAR(10), GETDATE(), 108) <= CONVERT(VARCHAR(10),(DATEADD(minute, 5, GETDATE())), 108))
BEGIN
-- Do something
END
ELSE
BEGIN
-- Do Next thing
END
Should I convert the time to other format before comparing and using in IF condition ? Please help
I you want to compare the time portions, you can cast() your values as time, like:
cast(getdate() as time) <= cast(dateadd(minute, 5, starttime) as time)
The reason why you want to do this is rather unclear; beware that, with this techinque, unexpected things may happen when starttime has a time portion that is greater than 23:55.

SQL IF statement for todays date

I'm trying to create a condition for my SQL, that shows a 1 if that row reflects today's day.
case when A.EntryDate = GETDATE() then '1' else '0' end as Today
That's accepted but it doesn't show anything but zeros. I've only worked with Access SQL and this one seems to dislike Date()
I've been looking all around for answers and I cannot seem to find one.
The GetDate() method return datetime. To compare today's date you need to convert datetime to date.
case when cast(A.EntryDate as date) = cast(getdate() as date) then 1 else 0 end

SQL Server : select count of Todays Transactions

I was wondering if someone could help me as I can't seem to find an answer to the following that I have been searching for.
Select
Count(pm1.number) As number
From
SCenter.probsummarym1 As pm1
Where
pm1.open_time >= Today()
I have the above that works great if I put in the date as '01-05-2015'
But I want today's date each day when it refreshes.
Sorry if this is pretty basic but I am just lost on this one
GETDATE() will return the current date and time.
You may then use a CAST() or CONVERT() to strip the time value and be left with just the date, ie.
SELECT CONVERT(VARCHAR(10), GETDATE(), 110)
The above code would return 05-19-2015 for today.
Select
Count(pm1.number) As number
From SCenter.probsummarym1 As pm1
Where
pm1.open_time >= GETDATE() //or CONVERT(VARCHAR(10), GETDATE(), 110)

SQL Server: Get data for only the past year

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])