Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
884 views
in Technique[技术] by (71.8m points)

tsql - How can I determine in SQL Server if a dateTime range overlaps another

We have eg. following table

| ID | startDateTime       | endDateTime         |
+----+---------------------+---------------------|
|  1 | 2010-01-01 10:30:00 | 2010-01-01 11:00:00 |
|  2 | 2010-01-01 10:30:00 | 2010-01-01 11:30:00 |
|  3 | 2010-01-01 11:00:00 | 2010-01-01 11:30:00 |
|  4 | 2010-01-01 11:00:00 | 2010-01-01 12:00:00 |
|  5 | 2010-01-01 11:30:00 | 2010-01-01 12:00:00 |
|  6 | 2010-01-01 10:30:00 | 2010-01-01 12:00:00 |

I will eg. query against with

@startDateTime 2010-01-01 11:00:00
@endDateTime 2010-01-01 11:30:00

I want to get following IDs: 2, 3, 4, 6

My brain is way to wacky to produce the correct statement ... :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do like this

declare @T table (ID int, startDateTime datetime, endDateTime datetime)

insert into @T values
(  1 , '2010-01-01 10:30:00' , '2010-01-01 11:00:00'),
(  2 , '2010-01-01 10:30:00' , '2010-01-01 11:30:00'),
(  3 , '2010-01-01 11:00:00' , '2010-01-01 11:30:00'),
(  4 , '2010-01-01 11:00:00' , '2010-01-01 12:00:00'),
(  5 , '2010-01-01 11:30:00' , '2010-01-01 12:00:00')

declare @startDateTime datetime
declare @endDateTime datetime


set @startDateTime = '2010-01-01 11:00:00'
set @endDateTime = '2010-01-01 11:30:00'

select *
from @T
where
  startDateTime < @endDateTime and
  endDateTime > @startDateTime

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...