日期:2014-05-17  浏览次数:20406 次

来个高手,这样的SQL语句应该怎么写?

--表结构
CREATE TABLE [dbo].[ERPZJPhaseTime](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [bianhao] [int] NOT NULL,
    [phase] [int] NULL,
    [phasename] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
    [starttime] [smalldatetime] NULL,
    [endtime] [smalldatetime] NULL,
    [days] [int] NULL,
    [bzstate] [int] NULL,
    [shstate] [int] NULL,
    [AchieveState] [int] NULL,
    [category] [int] NULL,
    [orderid] [int] NULL)
--测试用数据
insert ERPZJPhaseTime (id,bianhao,phase,phasename,starttime,endtime,days,bzstate,shstate,AchieveState,category,orderid)  values ( 2,2,1,NULL,'2012-07-04 00:00:00.000','2012-07-05 00:00:00.000',2,NULL,NULL,NULL,2,1)
insert ERPZJPhaseTime (id,bianhao,phase,phasename,starttime,endtime,days,bzstate,shstate,AchieveState,category,orderid)  values ( 3,2,2,NULL,'2012-07-06 00:00:00.000','2012-07-08 00:00:00.000',3,NULL,NULL,NULL,2,1)
insert ERPZJPhaseTime (id,bianhao,phase,phasename,starttime,endtime,days,bzstate,shstate,AchieveState,category,orderid)  values ( 4,2,3,NULL,'2012-07-10 00:00:00.000','2012-07-13 00:00:00.000',4,NULL,NULL,NULL,2,1)

要求:表中已有bianhao=2的3个时间段,它们是一个整体,也就是说表中原有数据bianhao相同的要按整体看待。现在我将要插入一行新的时间段,要求就是不能产生重复时间。如果重复,新增的时间段不变动,表中原有的时间将向后顺延。
--测试用代码

declare  @starttime smalldatetime ,@endtime smalldatetime ,@days int ,@category int ,@effectrow int
set @starttime ='2012/07/03';set @endtime='2012/07/05';set @days=3; set @bianhao=2;


以下内容是我想的思路,仅供参考。
先检测时间是否存在冲突(@starttime between starttime and endtime or @endtime between starttime and endtime),存在冲突则依情况一和二来处理。
情况一:starttime >=@startime,时间接着新增的时间向后移动;情况二:@starttime > starttime and @starttime <=endtime.将冲突所在行截为两段。

我的QQ55585811,写出来我给您充话费,谢谢!
------最佳解决方案--------------------
null
------其他解决方案--------------------
例 (4,5)(6,8)(10,13)

现在要写入的数据为(1,3),则直接插入。
(1,4)则变为 (1,4) (5,6) (7,9) (11,14)
(1,6)则变为 (1,6) (7,8) (9,10) (12,16)
(7,7)则变为 (4,5) (6,6) (7,7) (8,9) (11,14)