We help IT Professionals succeed at work.

SQL subtract two times to get minutes - SQL Server 2008

robthomas09
robthomas09 used Ask the Experts™
on
Hello experts.

I have two string variables that I need to subtract to find their times, and need some help with the syntax please.

DECLARE @S1 varchar(10)  = '09:15 AM'
DECLARE @S2 varchar(10)  = '10:15 AM'
DECLARE @S3 int

set @S3 = @s1 - @s2

select @s3 -- would like the answer to be 60 (minutes).

Thoughts?

Thanks

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2010
Commented:
SET @S3 = DATEDIFF(minute, CONVERT(datetime, @S1), CONVERT(datetime, @S2))
Som TripathiDatabase Administrator
Commented:
Hi,

Please try below code  -

DECLARE @S1 varchar(10)  = '09:15 AM'
DECLARE @S2 varchar(10)  = '10:15 AM'
DECLARE @S3 int

SET @S3= datediff( MINUTE, cast( @s1 as datetime) , cast( @s2 as datetime) )

SELECT @S3

Author

Commented:
Thanks!