我有一个表,其中包含用于存储服务开始时间和结束时间的列(我没有日期和时间,只有一周中的某一天)。考虑到服务周一开始,周二结束,我必须检查一周是否有时间。有人能帮助我吗?
CREATE TABLE #Calendar (
Name VARCHAR(100),
DayWeek INT,
HourStart TIME,
HourEnd TIME
);
INSERT INTO #Calendar (Name, DayWeek, HourStart, HourEnd)
VALUES ('Make a Cake', 1, '19:00:00', '07:00:00');
INSERT INTO #Calendar (Name, DayWeek, HourStart, HourEnd)
VALUES ('Make a cookie', 1, '07:00:00', '19:00:00');
INSERT INTO #Calendar (Name, DayWeek, HourStart, HourEnd)
VALUES ('Make a cookie', 2, '19:00:00', '23:00:00');
答案 0 :(得分:1)
好的,这必须有效。它显示每一行都有时间冲突;如果你取消注释它将显示没有冲突的行的最后一个
declare @test_DateTimeStart datetime=dateadd(day,4,'20:00:00') -- Check from Monday 20:00
declare @test_DateTimeEnd datetime=dateadd(day,5,'20:00:00') -- Check to Tuesday 20:00
select q2.result,c.*
from
#Calendar c
cross apply
( select
dateadd(day,DayWeek,convert(datetime,HourStart)) as DateTimeStart,
dateadd(day,DayWeek+1,convert(datetime,HourEnd)) as DateTimeEnd
)q
cross apply (select
case when exists
(
select 1 from #Calendar c2 where
(@test_DateTimeStart>DateTimeStart and @test_DateTimeStart<DateTimeEnd)
or
(@test_DateTimeEnd >DateTimeStart and @test_DateTimeEnd <DateTimeEnd)
)
then 'Time is taken due to this row -->'
else 'Time is free due to this row -->'
end as result
)q2
--where result='Time is taken due to this row -->'
答案 1 :(得分:0)
这将解决它。它将无法使用索引,因为它在比较时使用列计算:
DECLARE @from time = '22:59', @to time = '23:01'
DECLARE @DayWeek int = 2
;WITH CTE as
(
SELECT
dateadd(d, @DayWeek, cast(@from as datetime)) startdate,
dateadd(d,
CASE WHEN @to < @from
THEN @DayWeek + 1
ELSE @DayWeek
END,
cast(@to as datetime)) enddate
)
SELECT CASE WHEN
not exists
(
SELECT *
FROM #Calendar c
WHERE cte.startdate < dateadd(d, CASE WHEN HourEnd < HourStart
THEN DayWeek + 1 ELSE DayWeek END, cast(HourEnd as datetime))
AND cte.enddate > dateadd(d, DayWeek, cast(HourEnd as datetime))
) THEN 'Available' ELSE 'Not available' END
FROM CTE
答案 2 :(得分:-1)
使用以下代码获取当天的实时日期。然后与您的保存数据进行比较
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com");
var response = myHttpWebRequest.GetResponse();
string todaysDates = response.Headers["date"];
return DateTime.ParseExact(todaysDates,"ddd, dd MMM yyyy HH:mm:ss'GMT'",CultureInfo.InvariantCulture.DateTimeFormat,DateTimeStyles.AssumeUniversal).DayOfWeek;