是一个教室使用方面的冲突检测的SQL语句
首先是表一:
教室表编号  教室 最大使用班级数(也就是这个教室在一天只能允许几个班级使用)
001    中文     2教室使用情况表
教室编号   班级    开始日期      结束日期  
001          A      2006-03-01     2006-03-28
001          B      2006-03-01     2006-03-06
001          c      2006-03-07     2006-03-28上面的内容说明了,在2006-03-01到2006-03-28之间有三个班,但每天保证都是在一个教室里不超过两个班上课(教室表中限定),
我现在,想传入条件,教室编号,开始日期,与结束日期,三个条件,检测教室使用是否冲突(即超过教室表里的最大班级数的约定),想了一天也没有好的方法,因为是时间范围与时间范围的比较,希望高手给解。特别注明,此乃本世纪最难SQL语句。希望大家用存储过程做,如果没有冲突返回0,有冲突返回1,

解决方案 »

  1.   

    CREATE PROCEDURE testqw  @classid char(10), @begindate char(10), @enddate char(10)  as
    declare @numall int,@num int
    create table #class (classid char(10),name char(20),num int  )
    insert into #class
    select '001','中文',2 union all
    select '002','数学',2 union all
    select '003','英语',3 create table #classuser (classid char(10),banji char(20),begindate char(10),enddate char(10))
    insert into #classuser
    select '001','A','2006-03-01','2006-03-28' union all
    select '001','B','2006-03-01','2006-03-06' 
    --select '001','C','2006-03-07','2006-03-28' select  @numall=count(*)
    from #class
    where classid=@classid select @num=count(*) 
    from #classuser
    where classid=@classid
    and begindate>=@begindate
    and enddate>=@enddate

    if @numall>=@num 
    print '0' if @numall<@num 
    print '1'
    GO
      

  2.   

    修改后:
    CREATE PROCEDURE testqw  @classid char(10), @begindate char(10), @enddate char(10)  as
    declare @numall int,@num int
    create table #class (classid char(10),name char(20),num int  )
    insert into #class
    select '001','中文',2 union all
    select '002','数学',2 union all
    select '003','英语',3 create table #classuser (classid char(10),banji char(20),begindate char(10),enddate char(10))
    insert into #classuser
    select '001','A','2006-03-01','2006-03-28' union all
    select '001','B','2006-03-01','2006-03-06' 
    --select '001','C','2006-03-07','2006-03-28' select  @numall=count(*)
    from #class
    where classid=@classid select @num=count(*) 
    from #classuser
    where classid=@classid
    and begindate>=@begindate
    and enddate>=@enddate

    if @numall>@num 
    print '0' if @numall<=@num 
    print '1'
    GO
      

  3.   

    select * from 教室表 t1
    where 
    (
    select count(*) from 教室使用情况表 t2
    where  t2.教室编号=t1.教室编号
    and
    (
    (@Begindate>=t2.开始日期 and @Enddate>=t2.结束日期)
    or (@Begindate>=t2.开始日期 and @Enddate>=t2.结束日期)
    )
    )>2上面语句可以查出你指定日期范围内的所有教室如果要查指定教室的只要加个条件就可以了