我现在有这么一个需求.
1.在数据库内有二个字段start and end,都为数值型
2.我在添加一个数值时要检查我添加的start和end 是否已经在数据中的strat和end 的范围之内.
例如:现大数据库内已经有的数据是start=100,end=1000.
那么我在输入start=101,end=1001时会检查到这个数字范围已经包涵了我已经的范围,同理,strat=101,end=999也是不可以的.
我大概知道有多少个条件可以限制数据的输入,但我想应该会有一个更好的算法来计算这个问题,但是我想不到,请那位商手帮我一下,在此感谢.

解决方案 »

  1.   

    插入数据库之前先检查
    select count(*) from tbname where 
    (101 between start and end) or (999  between start and end);
    如果返回结果>0,说明范围重复,不能增加。
      

  2.   

    SELECT [id]
          ,[start]
          ,[end]
      FROM [test].[dbo].[table1] where 15 between start and [end]
    同理:
    if not exists(select * from table1 where (@start between start and [end]) or (@end between start and [end]) begin
    insert into ...........
    end
      

  3.   

    感觉你的要求就是没有交集。
    select count(*) into nCount form table 
    where (start >= :newstart and start <= :newend) 
    or (start <= :newstart and end >= :newstart)  if (nCount > 0) 

      //有交集
    }
    else
    {
      // insert 
    }
      
      

  4.   

    //写一个检测方法,调用该存储过程来检测
    create proc usp_check_duplicate
    @i_start int,
    @i_end int,
    @i_out int output --0=无重复/1=已重复
    as
    if not exists(select 1 from tb where (iend<@i_end and iend>@i_start) or (istart>@i_start and istart<@i_end) or (istart<@i_start and iend>@i_end))
        set @i_out=0
    else
        set @i_out=1
    return @i_out
      

  5.   

    select max(start)
    select min(end)