你的位置:首页 > 数据库

[数据库]SQL Server 2008 R2——查找最小nIndex,nIndex存在而nIndex+1不存在


=================================版权声明=================================

版权声明:原创文章 谢绝转载 

请通过右侧公告中的“联系邮箱(wlsandwho@foxmail.com)”联系我

勿用于学术性引用。

勿用于商业出版、商业印刷、商业引用以及其他商业用途。                   

 

本文不定期修正完善。

本文链接:http://www.cnblogs.com/wlsandwho/p/4930415.html

耻辱墙:http://www.cnblogs.com/wlsandwho/p/4206472.html

=======================================================================

最为一只C++,每天回答SQL Server的问题感觉压力还是蛮大的。

=======================================================================

做戏做全套,送佛送到西。为了便于学习研究,必然是要写全套示例代码的。

 1 ------------------------------------------------------------------------------------- 2 --by wls 3 --非专业SQL 不求高效 但求能跑 4 USE tempdb 5 GO 6  7 ------------------------------------------------------------------------------------- 8 IF OBJECT_ID (N't_MaxInMinContinuousArr', N'U') IS NOT NULL 9 DROP TABLE t_MaxInMinContinuousArr;10 GO11 12 CREATE TABLE t_MaxInMinContinuousArr(SNId INTEGER PRIMARY KEY,SomeDate DATETIME)13 GO14 15 -------------------------------------------------------------------------------------16 DECLARE  @i INT17 SET @i = 666      --SNId起始值18 19 DECLARE @TestScale INTEGER20 SET @TestScale=500000+@i  --数据规模21 22 DECLARE @t1 DATETIME ,23     @t2 DATETIME ,24     @dd0 INT ,25     @dayadd INT ,26     @tRes DATETIME27     28 SET @t1 = '2010-01-01 00:00:00'29 SET @t2 = '2025-12-31 00:00:00'30 SET @dd0 = DATEDIFF(dd, @t1, @t2)31 32 WHILE @i < @TestScale  --数据规模33   BEGIN 34    SET @dayadd = @dd0 * RAND() 35    SET @tRes = DATEADD(dd, @dayadd, @t1) + RAND()  36     37    INSERT  INTO t_MaxInMinContinuousArr VALUES(@i , @tRes)38        39    SET @i = @i + 140   END41 GO42  43 --SELECT TOP 100 * FROM t_MaxInMinContinuousArr44 --GO45 46 -------------------------------------------------------------------------------------47 --Delete some SNId randomly48 DECLARE @TestScale INTEGER49 SET @TestScale=500000  --数据规模50 DELETE FROM t_MaxInMinContinuousArr WHERE SNId=678--(SELECT abs(checksum(newid()))%@TestScale + 1)51 DELETE FROM t_MaxInMinContinuousArr WHERE SNId=667--(SELECT abs(checksum(newid()))%@TestScale + 1)52 53 GO54 55 --SELECT TOP 100 * FROM t_MaxInMinContinuousArr56 --GO57 58 -------------------------------------------------------------------------------------59 --now find the SNId that SNId+1 is missing.60 WITH TMinAndMaxSNId61 AS(62 SELECT MIN(SNId) AS MinSNId,MAX(SNId) AS MaxSNId FROM t_MaxInMinContinuousArr  --The min and max SNId63 ),64 TContinuousId65 AS66 (67 SELECT number AS SNIdCmped FROM master..spt_values,TMinAndMaxSNId WHERE type='p' AND number >=TMinAndMaxSNId.MinSNId AND number <=TMinAndMaxSNId.MaxSNId68 )69 SELECT MIN(res.SNIdCmped)-1 FROM70 (71 SELECT  SNIdCmped FROM TContinuousId72 EXCEPT 73 SELECT  SNId FROM t_MaxInMinContinuousArr) AS res 74 GO

  附上执行计划

 

我也不知道这代码能不能用,先发表了后续慢慢改吧。