日期:2014-05-17 浏览次数:20450 次
declare @T table (col datetime) insert into @T select '20010101' union all select '20010402' union all select '20010523' union all select '20010623' union all select '20010809' union all select '20010911' union all select '20011112' union all select '20011214' union all select '20020219' union all select '20020326' union all select '20020505' union all select '20020611' union all select '20020915' union all select '20021230' select a.col as c1,b.col as c2 from @T a right join ( select dateadd(month,number,'20010101') as col from master..spt_values where type='p' and number < 24) b on convert(varchar(7),a.col,120)=convert(varchar(7),b.col,120) /* c1 c2 ----------------------- ----------------------- 2001-01-01 00:00:00.000 2001-01-01 00:00:00.000 NULL 2001-02-01 00:00:00.000 NULL 2001-03-01 00:00:00.000 2001-04-02 00:00:00.000 2001-04-01 00:00:00.000 2001-05-23 00:00:00.000 2001-05-01 00:00:00.000 2001-06-23 00:00:00.000 2001-06-01 00:00:00.000 NULL 2001-07-01 00:00:00.000 2001-08-09 00:00:00.000 2001-08-01 00:00:00.000 2001-09-11 00:00:00.000 2001-09-01 00:00:00.000 NULL 2001-10-01 00:00:00.000 2001-11-12 00:00:00.000 2001-11-01 00:00:00.000 2001-12-14 00:00:00.000 2001-12-01 00:00:00.000 NULL 2002-01-01 00:00:00.000 2002-02-19 00:00:00.000 2002-02-01 00:00:00.000 2002-03-26 00:00:00.000 2002-03-01 00:00:00.000 NULL 2002-04-01 00:00:00.000 2002-05-05 00:00:00.000 2002-05-01 00:00:00.000 2002-06-11 00:00:00.000 2002-06-01 00:00:00.000 NULL 2002-07-01 00:00:00.000 NULL 2002-08-01 00:00:00.000 2002-09-15 00:00:00.000 2002-09-01 00:00:00.000 NULL 2002-10-01 00:00:00.000 NULL 2002-11-01 00:00:00.000 2002-12-30 00:00:00.000 2002-12-01 00:00:00.000 */
------解决方案--------------------
CREATE TABLE TABLE5(DocDate DATETIME) INSERT INTO TABLE5 SELECT '20010101' UNION ALL SELECT '20010402' UNION ALL SELECT '20010523' UNION ALL SELECT '20010623' UNION ALL SELECT '20010809' UNION ALL SELECT '20010911' UNION ALL SELECT '20011112' UNION ALL SELECT '20011214' UNION ALL SELECT '20020219' UNION ALL SELECT '20020326' UNION ALL SELECT '20020505' UNION ALL SELECT '20020611' UNION ALL SELECT '20020915' UNION ALL SELECT '20021230' DECLARE @MINMONTH DATETIME DECLARE @MAXMONTH DATETIME DECLARE @TMEPMONTH DATETIME SELECT @MINMONTH =MIN(DocDate),@MAXMONTH =MAX(DocDate) FROM TABLE5 CREATE TABLE #TABLE6(DocDate DATETIME) WHILE DATEDIFF(MONTH,@MINMONTH,@MAXMONTH)>0 BEGIN SET @MINMONTH =DATEADD(MONTH,1,@MINMONTH) IF NOT EXISTS(SELECT 1 FROM TABLE5 WHERE CONVERT(CHAR(7),DocDate,111) = CONVERT(CHAR(7),@MINMONTH,111) ) BEGIN INSERT INTO #TABLE6 SELECT @MINMONTH END END SELECT * FROM #TABLE6 DROP TABLE #TABLE6 /* DocDate ----------------------- 2001-02-01 00:00:00.000 2001-03-01 00:00:00.000 2001-07-01 00:00:00.000 2001-10-01 00:00:00.000 2002-01-01 00:00:00.000 2002-04-01 00:00:00.000 2002-07-01 00:00:00.000 2002-08-01 00:00:00.000 2002-10-01 00:00:00.000 2002-11-01 00:00:00.000 (10 行受影响) */