取日期相交記錄

declare @Holiday table
 (
 ID int identity(1,1),
 SDate DateTime,
 EDate DateTime,
 Remark varchar(30) 
 )

insert into @Holiday(SDate, EDate, Remark) values('2012-03-10', '2012-03-15', 'A')
--
insert into @Holiday(SDate, EDate, Remark) values('2012-04-01', '2012-04-04', 'B') 
insert into @Holiday(SDate, EDate, Remark) values('2012-04-10', '2012-04-11', 'C')
insert into @Holiday(SDate, EDate, Remark) values('2012-04-28', '2012-05-01', 'D')
--
insert into @Holiday(SDate, EDate, Remark) values('2012-05-05', '2012-05-10', 'F')

-- 设定取日期范围
declare @SDate DateTime, @EDate DateTime
select @SDate = '2012-04-01', @EDate = '2012-04-30'

-- 取日期相交記錄(日期有效记录)
select
 (case when @SDate >= SDate then @SDate else SDate end) as SDate, -- 开始日期取大
 (case when @EDate <= EDate then @EDate else EDate end) as EDate, -- 结束日期取小
 Remark
from @Holiday
where
 (
 (@SDate between SDate and EDate)
 or
 (@EDate between SDate and EDate)
 or
 (@SDate <= SDate and EDate <= @EDate)
 )


 

你可能感兴趣的:(c,table,insert)