views:

71

answers:

1

Here is my table. I need a query which returns the shift id for a specified time
How can I get the value?

shift_ID   shift_From                shift_To
1          2010-09-21 10:00:00.000   2010-09-21 18:10:00.000
2          2010-09-21 20:00:00.000   2010-09-21 05:00:00.000

Suppose I am giving 02:00:00 as input I need to get the shift ID as 1. How can I do this?

+1  A: 

Try:

SELECT shift_ID
FROM time_shift
WHERE
DATEDIFF(hour, shift_From, shift_To) = 2 -- your input

See more about DATEDIFF on MSDN

The first argument is the time part you're specifying to DATETIFF (hour, minute, second).

If your input is strictly like 02:00:00 you need to parse it to determine what specify as the first argument.


To determine does the specified date belong between 2 others, use:

SELECT shift_ID
FROM time_shift
WHERE
    CAST(shift_From AS TIME) < CAST(@input AS TIME)
AND
    CAST(@input AS TIME) < CAST(shift_To AS TIME)
-- you can specify operators inclusiveness, i.e. <= >= etc
-- or
CAST(@input AS TIME) BETWEEN (CAST(shift_From AS TIME), CAST(shift_To AS TIME))

See more about TIME on MSDN

abatishchev
I need to check whether the input time is between the shift to and shift from. DateDiff will returns the duration of the shift
Vishnu K B
@Hari: See my updated post
abatishchev
@abatishchev Here I want to compare the time without considering date.Your query didn't returns any thing :(
Vishnu K B
@Hari: Oops, sorry, forgot about that. See my updated post.
abatishchev
which type i need to specify the input i tried this way Declare @input time='02:00:00'SELECT shift_IDFROM tblEmpShiftWHERE CAST(shift_From AS TIME) < CAST(@input AS TIME)AND CAST(@input AS TIME) < CAST(shift_To AS TIME) But it won't return anything
Vishnu K B
@Hari: `BETWEEN` works strange for `TIME`: `SELECT CASE WHEN CAST('02:00:00' AS TIME) BETWEEN CAST('10:00:00.000' AS TIME) AND CAST('18:10:00.000' AS TIME) THEN 1 ELSE 0 END` returns 0
abatishchev
@Hari: I did some investigation and here's the result: It ok that `02:00:00` (2am) is not between 10am and 18pm because it's really not between :) So you should not use `BETWEEN`. I think you should use `DATEDIFF`.
abatishchev
@abatishchev : Thanks for ur help :)
Vishnu K B
Finally I got the answer select es.shift_ID from tblEmpShift es where @time BETWEEN Convert(TIME,es.shift_From) AND CONVERT(Time,es.shift_To)
Vishnu K B