各位大侠 ,小弟现在遇见一个这样的问题建立了一个存储过程,参数是课程ID的集合首先我以逗号分隔课程ID的集合 ,同时去关联课程表,得到一个小的课程表(也就是根据传进来的参数得到的)我现在想做的事情是 ,去从课程表(总的课程表)查找出 教室ID 一样的,并且上课时间一样的,还有就是开课和下课时间不冲突的,并且课程ID 不等于小的课程表里的ID总的功能也就是判断排课时有没有教室冲突 ,我以前的做法是一次传进来一个课程ID ,去查库,这样就得查找几百次或者上千次,我现在想用一个查询实现 ,代码如下:declare @ids varchar(5000) --课程ID集合
set @ids = '1880378,1880382,1880386, declare @Lessons table
(
nLessonID int
)insert into @Lessons
select * from Split(@ids) select P.*,'教室冲突' as CollidedType from
(
select B.* from @Lessons A left join bs_lesson as B
on A.nLessonID = B.id
) T
INNER join bs_lesson P
on T.dtDate = P.dtDate
and T.sRoomCode = P.sRoomCode
and T.id <> P.id -- 不判断自身,允许覆盖(允许重排)
and P.sRoomCode is not null and P.sRoomCode <> ''
and not (P.SectBegin >= T.SectEnd or P.SectEnd <= T.SectBegin ) 但是现在查询出来的结果总是有出入 ,请大侠们帮忙看看 我这里写的有什么问题 ,如果有其他好的方法的话,也请赐教下,先再这里谢过了
set @ids = '1880378,1880382,1880386, declare @Lessons table
(
nLessonID int
)insert into @Lessons
select * from Split(@ids) select P.*,'教室冲突' as CollidedType from
(
select B.* from @Lessons A left join bs_lesson as B
on A.nLessonID = B.id
) T
INNER join bs_lesson P
on T.dtDate = P.dtDate
and T.sRoomCode = P.sRoomCode
and T.id <> P.id -- 不判断自身,允许覆盖(允许重排)
and P.sRoomCode is not null and P.sRoomCode <> ''
and not (P.SectBegin >= T.SectEnd or P.SectEnd <= T.SectBegin ) 但是现在查询出来的结果总是有出入 ,请大侠们帮忙看看 我这里写的有什么问题 ,如果有其他好的方法的话,也请赐教下,先再这里谢过了
这个查询 加上 distinct 没有问题
这个是一个朋友回的贴 大家看说的对吗 应该怎么改呢
比如P.SectEnd <= T.SectBegin意思是
下课时间早于下节课的上课时间,
但是很可能这个课的
上课时间早于某节课的下课时间
-----------
这个也没问题,我试过,这样的结果就是这条数据会出现两次
这样改改好些
select P.*,'教室冲突' as CollidedType from bs_lesson P
where exists(select 1 from
(
select B.* from @Lessons A left join bs_lesson as B
on A.nLessonID = B.id
) T
where T.dtDate = P.dtDate
and T.sRoomCode = P.sRoomCode
and T.id <> P.id -- 不判断自身,允许覆盖(允许重排)
and P.sRoomCode is not null and P.sRoomCode <> ''
and not (P.SectBegin >= T.SectEnd or P.SectEnd <= T.SectBegin )
)---测试:--建立测试环境
IF OBJECT_ID('tb') IS NOT NULL DROP TABLE tb
GO
CREATE TABLE tb
(
id int identity,
dt1 datetime,
dt2 datetime,
CONSTRAINT PK_TB PRIMARY KEY (id)
)
GO
INSERT TB
SELECT '2010-01-01 7:00','2010-01-01 9:00' union all
SELECT '2010-01-01 8:00','2010-01-01 10:00' union all
SELECT '2010-01-01 9:20','2010-01-01 11:00' union all
SELECT '2010-01-01 13:00','2010-01-01 15:00'
--查询
select a.* from tb a
where exists(
select 1 from tb b where a.id<>b.id
and not (a.dt1>=b.dt2 or a.dt2<=b.dt1)
)
--结果
/*
id dt1 dt2
----------- ----------------------- -----------------------
1 2010-01-01 07:00:00.000 2010-01-01 09:00:00.000
2 2010-01-01 08:00:00.000 2010-01-01 10:00:00.000
3 2010-01-01 09:20:00.000 2010-01-01 11:00:00.000(3 行受影响)*/