日期:2014-05-18 浏览次数:20796 次
--如何用"最小缺失数"实现确实日期的自动补全 -->生成测试数据: GO IF OBJECT_ID('TBL')IS NOT NULL DROP TABLE TBL GO CREATE TABLE TBL( 日期 DATE, 备注 VARCHAR(100) ) GO INSERT TBL SELECT '2012-03-02','B' UNION ALL SELECT '2012-03-05','C' UNION ALL SELECT '2012-03-06','D' UNION ALL SELECT '2012-03-07','E' UNION ALL SELECT '2012-03-09','F' UNION ALL SELECT '2012-03-11','G' UNION ALL SELECT '2012-03-12','H' UNION ALL SELECT '2012-03-13','I' UNION ALL SELECT '2012-03-15','J' UNION ALL SELECT '2012-03-19','K' UNION ALL SELECT '2012-03-20','L' GO IF OBJECT_ID('P_SP')IS NOT NULL DROP PROC P_SP GO CREATE PROC P_SP @STARTTIME DATE,--用来传入起始日期 @ENDTIME DATE--用来传入截止日期 AS DECLARE @SQL VARCHAR(100) SET @SQL='SELECT * FROM TBL ORDER BY 日期' DECLARE @MINMISS DATE SET @MINMISS=( SELECT COALESCE(DATEADD(DD,1,MIN(A.日期)), @STARTTIME) AS MISSING FROM TBL A WHERE NOT EXISTS( SELECT * FROM TBL B WHERE B.日期=DATEADD(DD,1,A.日期)) AND EXISTS ( SELECT 1 FROM TBL WHERE 日期=@STARTTIME)) PRINT @MINMISS WHILE @MINMISS<=@ENDTIME BEGIN INSERT TBL(日期) VALUES(@MINMISS) SELECT @MINMISS=( SELECT DATEADD(DD,1,MIN(A.日期)) FROM TBL A WHERE NOT EXISTS( SELECT * FROM TBL B WHERE B.日期=DATEADD(DD,1,A.日期)) ) END EXEC(@SQL) EXEC P_SP '2012-03-01','2012-03-20' /* 日期 备注 2012-03-01 NULL 2012-03-02 B 2012-03-03 NULL 2012-03-04 NULL 2012-03-05 C 2012-03-06 D 2012-03-07 E 2012-03-08 NULL 2012-03-09 F 2012-03-10 NULL 2012-03-11 G 2012-03-12 H 2012-03-13 I 2012-03-14 NULL 2012-03-15 J 2012-03-16 NULL 2012-03-17 NULL 2012-03-18 NULL 2012-03-19 K 2012-03-20 L */ 类似问题,刚刚写好的,给你参考一下
------解决方案--------------------
其它字段插入时怎么处理,给出输入格式
------解决方案--------------------
假如你的1到N在某个表tb1,要插入表tb2
insert into tb2 select ... from tb1 where not exists(select 1 from tb2 where tb2.关键字 = tb1.关键字)
如果不存在表tb1,则可以使用系统表sysobjects来生成你的序列表.
select (select count(1) from sysobjects m where m.id < n.id) + 1 as px from sysobjects n