Performing date/time subtraction in SQL Server - sql

I have four columns in a table:
date entered, time entered, date completed, time completed
I would like to know the difference between date/time ENTERED and date/time COMPLETED
For example
date entered = 1/1/2001
time entered = 10:00
time completed = 1/2/2001
time completed = 11:00
The difference is 25 hours.
How can I perform this computation with a select statement?
I tried this:
DATEDIFF(hh,dateadd(hh,[Time Entered],[Date Entered]),dateadd(hh,[Time Completed],[Date Completed]) ) AS [Hours]
and got the following error:
Msg 8116, Level 16, State 1, Line 2
Argument data type time is invalid for argument 2 of dateadd function.

Declare #dateentered date = '20010101'
Declare #timeentered time = '10:00'
Declare #datecompleted date = '20010102'
Declare #timecompleted time = '11:00'
select datediff(hh, #dateentered + cast(#timeentered as datetime),
#datecompleted + cast(#timecompleted as datetime))
So, in terms of your tables' columns:
select datediff(hh, [date entered] + cast([time entered] as datetime),
[date completed] + cast([time completed] as datetime)) as [Hours]

select datediff(hour,'1/1/2001 10:00','1/2/2001 11:00')

Try
select DateDiff(ss, [Date Entered] + convert(datetime, [Time Entered]),
[Date Completed] + convert(datetime, [Time Completed]))
from myTable
to get the result in seconds.
Here's a standalone example:
declare #dateentered date = '1/1/2001'
declare #timeentered time = '10:00'
declare #datecompleted date = '1/2/2001'
declare #timecompleted time = '11:00'
select DateDiff(ss,
#dateentered + convert(datetime, #timeentered),
#datecompleted + convert(datetime, #timecompleted))
And of course you can specify different dateparts as specified for DATEDIFF.

Use DateDiff

DECLARE #StartDate DATETIME
Declare #EndDate DATETIME
declare #startime datetime
declare #endime datetime
SET #StartDate = '2001-01-01'
set #startime = '10:00'
SET #EndDate = '2001-01-02'
set #endime = '11:00'
set #StartDate = #StartDate + #startime
set #EndDate = #EndDate + #endime
--To get only Hours
SELECT DATEDIFF(hh, #StartDate,#EndDate ) AS [Hours];

Related

Why does my code execute IF block even if dates comparison fail?

Expiry Date = '2017-10-16' and ExpiryTime='12:00pm' in table and in our country Getdate is '2017-10-16' and currentdatetime is '2017-10-16 11:05:33.503'
but still, my code executes the IF condition which it should not. Why ?
Declare #ExpiryDate date
Declare #ExpiryTime varchar(10)
Set #ExpiryDate= (Select convert(varchar(11), ExpiryDate, 106) from Works where NIT_No= #NITNo and WorkNo= #WorkNo)
Set #ExpiryTime= (Select CAST(ExpiryTime as TIME(0)) from Works where NIT_No= #NITNo and WorkNo= #WorkNo)
IF(CONVERT(DATETIME,CONVERT(VARCHAR,#ExpiryDate,106)+ ' ' + #ExpiryTime) <= CONVERT(datetime, GETDATE()))
Begin
RAISERROR('Sorry, Expiry date and time has passed', 16, 10);
return;
End
12:00pm is translated to 00:00 in 24 hour format. If you combine the current date and 12:00pm, you expect the result to be midnight of the next day, but actually you get midnight of the current day.
That should work:
Declare #ExpiryDate date
Declare #ExpiryTime varchar(10)
Set #ExpiryDate= (Select convert(varchar(11), ExpiryDate, 106) from Works where NIT_No= #NITNo and WorkNo= #WorkNo)
Set #ExpiryTime= (Select CAST(ExpiryTime as TIME(0)) from Works where NIT_No= #NITNo and WorkNo= #WorkNo)
declare #dateTimeCombined datetime = dateadd(ms, datediff(ms, '00:00:00', #ExpiryTime), cast(#ExpiryDate as datetime))
IF #dateTimeCombined <= CONVERT(datetime, GETDATE())
Begin
RAISERROR('Sorry, Expiry date and time has passed', 16, 10);
return;
End

How to add date and time in SQL Server

I have two variables #date of type datetime and #time of type time. I want to add both to get another datetime variable. And I want to perform further calculations on it.
Ex:
Declare #date datetime
Declare #time time
I want something like this
#date = #date + #time (but not concatenation)
SELECT #Startdate = DATEADD(DAY, -1, #date )
Is there any way?
You can tranform your time to seconds and add them to your datetime value:
DECLARE #datetime DATETIME = GETDATE(),
#time TIME = '01:16:24',
#timeinseconds INT
PRINT 'we add ' + CAST(#time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,#datetime,120)+ ':'
SELECT #timeinseconds = DATEPART(SECOND, #time)
+ DATEPART(MINUTE, #time) * 60
+ DATEPART(HOUR, #time) * 3600
SET #datetime = DATEADD(SECOND,#timeinseconds,#datetime)
PRINT 'The result is: ' + CONVERT(VARCHAR,#datetime,120)
Output:
we add 01:16:24 to 2015-07-17 09:58:45:
The result is: 2015-07-17 11:15:09
The only thing you are missing is that #time needs to be cast back to a datetime before adding to #date.
declare #date datetime = '2022-05-26'
declare #time time = '09:52:14'
declare #Startdate datetime
set #date = #date + convert(datetime,#time)
SELECT #Startdate = DATEADD(DAY, -1, #date)
Produces:
If you need to take only date part from #date and time part from #time - can convert your #date and #time to strings, concatenate the values and convert back to datetime:
select cast(convert(nvarchar(20), #date, 104) + ' ' +
convert(nvarchar(20), #time, 108) as datetime2)
Or, alternatively, if you need to add time to datetime value, you can do something like:
select dateadd(ms,
datepart(ms, #time),
dateadd(ss,
datepart(ss, #time),
dateadd(mi,
datepart(mi, #time),
dateadd(hh, datepart(hh, #time), #date))))
First of all convert #date and #time variables to NVARCHAR(), then concat them and after It convert It to DATETIME datatype. After It you can use DATEADD function on It. Try in following:
DECLARE #date DATETIME
DECLARE #time TIME
SET #date = GETDATE()
SET #time = '10:12:13'
SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), #date, 110) + ' ' +
CONVERT(NVARCHAR(20), #time, 108) AS DATETIME))
OUTPUT (Today day -1 + time '10:12:13'):
2015-07-16 10:12:13.000
I'm not sure what's going on here, but if your variables are datetime and time types, this should work just fine:
declare #date datetime
declare #time time
set #date = '20150717'
set #time = '12:34:56'
set #date = #date + #time
select #date, DATEADD(DAY,-1,#date)
See SQL Fiddle
If the problem is that #date contains also time part, you can use:
set #date = convert(datetime, convert(date, #date)) + #time
Your code is correct.
DECLARE #date DATETIME = '1/1/2020'
DECLARE #time TIME = '1:00 pm'
DECLARE #Startdate DATETIME
SET #date = #date + #time
SELECT #Startdate = DATEADD(DAY, -1, #date)
#date = 2020-01-01 13:00:00.000
#Startdate = 2019-12-31 13:00:00.000
It isn't concatenating, it is adding them together. The time on #date is 0:00:00.000, so it might appear to be concatenating them. But change #date to '1/1/2020 1:00 am' and then:
#date = 2020-01-01 14:00:00.000
#Startdate = 2019-12-31 14:00:00.000

how to enter manual time stamp in get date ()

how to enter manual time stamp in get date () ?
select conver(varchar(10),getdate(),120)
returns 2010-06-07
now i want to enter my own time stamp in this like
2010-06-07 10.00.00.000
i m using this in
select * from sample table where time_stamp ='2010-06-07 10.00.00.000'
since i m trying to automate this query i need the current date but i need different time stamp can it be done .
You just want to append a time to your result? Like this?
select convert(varchar(10),getdate(),120) + ' 10.00.00.000'
or if you want to get it back to a DATETIME type:
select convert(datetime,convert(varchar(10),getdate(),120) + ' 10:00')
--SQL Server 2008
DECLARE #MyTime time, #MyDate date
SELECT #MyDate = GETDATE(), #MyTime = '10:00:00'
SELECT CAST(#MyDate AS datetime) + #MyTime
--SQL Server 2005 and before
DECLARE #MyTime datetime, #MyDate datetime
SELECT
#MyDate = DATEADD(day, 0, DATEDIFF(day, 0, GETDATE())),
#MyTime = '19000101 10:00:00'
SELECT #MyDate + #MyTime
"zero" date = 01 Jan 1900 in SQL Server
SELECT DATEADD(hh, 1, FLOOR(CAST(GETDATE() AS FLOAT)))
Once you have the floor of the date, you can add time to it.
DATEADD(datepart, number, date)

SQL need to subtract certain time from date parameter passed into query

I have a date parameter so the date and time can always change.
For this example the datetime is '2010-07-06 14:46:37.577'
I need to see how much time is between this date paramter and the time of '17:00:00.000'
The time of 5PM will never change but as I said the date paramter can change.
declare #MyDate datetime
set #MyDate = '2010-07-06 14:46:37.577'
select DATEDIFF(MINUTE, #MyDate, CONVERT(varchar(10), #Mydate, 101)+' 17:00:00')
DECLARE #DateParameter datetime
DECLARE #DateTime5PM datetime
SET #DateParameter = '2010-07-06 14:46:37.577'
SET #DateTime5PM = CAST(CONVERT(varchar, #DateParameter, 101) + ' 17:00' AS datetime)
SELECT DATEDIFF (MI, #DateParameter, #DateTime5PM)

Compare current date with stored datetime using month an year only

Using SQL Server 2005 I have a field that contains a datetime value.
What I am trying to do is create 2 queries:
Compare to see if stored datetime is of the same month+year as current date
Compare to see if stored datetime is of the same year as current date
There is probably a simple solution but I keep hitting brick walls using various samples I can find, any thoughts?
Thanks in advance.
Compare the parts of the date:
WHERE YEAR( columnName ) = YEAR( getDate() )
While the other answers will work, they all suffer from the same problem: they apply a transformation to the column and therefore will never utilize an index on that column.
To search the date without a transformation, you need a couple built-in functions and some math. Example below:
--create a table to hold our example values
create table #DateSearch
(
TheDate datetime not null
)
insert into #DateSearch (TheDate)
--today
select getdate()
union all
--a month in advance
select dateadd(month, 1, getdate())
union all
--a year in advance
select dateadd(year, 1, getdate())
go
--declare variables to make things a little easier to see
declare #StartDate datetime, #EndDate datetime
--search for "same month+year as current date"
select #StartDate = dateadd(month, datediff(month, 0, getdate()), 0), #EndDate = dateadd(month, datediff(month, 0, getdate()) + 1, 0)
select #StartDate [StartDate], #EndDate [EndDate], TheDate from #DateSearch
where TheDate >= #StartDate and TheDate < #EndDate
--search for "same year as current date"
select #StartDate = dateadd(year, datediff(year, 0, getdate()), 0), #EndDate = dateadd(year, datediff(year, 0, getdate()) + 1, 0)
select #StartDate [StartDate], #EndDate [EndDate], TheDate from #DateSearch
where TheDate >= #StartDate and TheDate < #EndDate
What the statement does to avoid the transformations, is find all values greater-than or equal-to the beginning of the current time period (month or year) AND all values less-than the beginning of the next (invalid) time period. This solves our index problem and also mitigates any issues related to 3ms rounding in the DATETIME type.
SELECT * FROM atable
WHERE
YEAR( adate ) = YEAR( GETDATE() )
AND
MONTH( adate ) = MONTH( GETDATE() )
It sounds to me like DATEDIFF is exactly what you need:
-- #1 same month and year
SELECT *
FROM your_table
WHERE DATEDIFF(month, your_column, GETDATE()) = 0
-- #2 same year
SELECT *
FROM your_table
WHERE DATEDIFF(year, your_column, GETDATE()) = 0
The datepart function lets you pull the bits you need:
declare #d1 as datetime
declare #d2 as datetime
if datepart(yy, #d1) = datepart(yy, #d2) and datepart(mm, #d1) = datepart(mm, #d2) begin
print 'same'
end
You can use something like this
a)
select *
from table
where MONTH(field) = MONTH(GetDATE())
and YEAR(field) = YEAR(GetDATE())
b)
select *
from table
where YEAR(field) = YEAR(GetDATE())