Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 DATEDIFF in Hours / Minutes

Author  Topic 

Jonny1409
Posting Yak Master

133 Posts

Posted - 2007-09-07 : 06:51:15
Hello,

I have a really quick syntax question please as I'm really new to SQL (as you can probably tell by the basic questions)

I am using Datediff to get the number of hours between two times :

datediff(hh, StartTime, EndTime) as length

However, this only shows whole hours as opposed to say 1 and a half hours between 12.00 and 1.30

Therefore I thought I'd use minutes and divide the result by 60.
This again, gives me the whole hours but not the minutes.

I've tried using CAST as float but I must be doing it wrong.

What would be the syntax for this please ?

Kristen
Test

22859 Posts

Posted - 2007-09-07 : 06:54:29
"I've tried using CAST as float but I must be doing it wrong."

If you do

SELECT 11 / 2

the result will be an integer, because both values are integers. That doesn;t change if you do

SELECT CONVERT(float, 11 / 2)

because the inner bit is still integer maths, whereas

SELECT CONVERT(float, 11) / CONVERT(float, 2)

will force a floating point division

EDIT: As KHTan points out below, if you have CONSTANT values you can force "floating point" by including a decimal, so:

SELECT 11 / 2 -- uses integer maths
SELECT 11.0 / 2.0 -- uses floating point maths


Kristen
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-09-07 : 06:55:19
find the diff of the time in minutes

datediff(minute, StartTime, EndTime)

then divide by 60.0 to get the time diff in hour



KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-09-07 : 08:09:35
Also read here why you think DATEDIFF returns the wrong result
http://www.sqlteam.com/article/datediff-function-demystified



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

Jonny1409
Posting Yak Master

133 Posts

Posted - 2007-09-07 : 08:24:51
Thanks again for all of your help.
Go to Top of Page
   

- Advertisement -