Check if a time is between two times (time DataType)

前端 未结 7 1403
我寻月下人不归
我寻月下人不归 2020-12-06 10:05

I have a table that has a column \"Created\" as a datetime.

I\'m trying to query to check if the time for the Created value is between two times.

The Created

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 10:23

    Let us consider a table which stores the shift details

    enter image description here

    Please check the SQL queries to generate table and finding the schedule based on an input(time)

    Declaring the Table variable

    declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)
    

    Adding values to Table variable

    insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
    insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
    insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'
    

    Creating another table variable with an additional field named "Flag"

    declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)
    

    Adding values to temporary table with swapping the start and end time

    insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

    Creating input variable to find the Shift

    declare @time time=convert(time,'10:12:40.3530000')
    

    Query to find the shift corresponding to the time supplied

    select myShift from @Temp where
    (@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

提交回复
热议问题