日期:2014-05-18 浏览次数:20579 次
declare @ym varchar(12),@y varchar(4),@m varchar(2),@c1 varchar(12),@c2 varchar(12),@c3 varchar(12) 
declare @y1 int,@y2 int,@m1 int ,@m2 int 
set @y1=DATEPART(year,@d1) 
set @y2=DATEPART(year,@d2) 
set @m1=DATEPART(month,@d1) 
set @m2=DATEPART(month,@d2) 
--select @y1,@y2,@m1,@m2 
declare @i int,@j int,@n1 int,@n2 int 
set @c1='' 
set @c2='' 
set @c3='' 
if @y2-@y1>1  
   return 
   
if @m1>9 
begin 
  if @m2+13-@m1>3  --m2与m1超过3个月
     return 
  else 
  begin  
    set @j=1 
    set @n1=@y1*100+@m1  --转为yyyymm的整数
    set @n2=@y2*100+@m2   
    set @i=@n1 
    while @i <= @n2 
    begin 
       set @ym=convert(varchar(6),@i)        
       if @j=1  
       set @c1=@ym 
       else   
       if @j=2  
       set @c2=@ym 
       else 
       set @c3=@ym   
       if convert(int,right(convert(varchar(12),@i),2))=12 --如果为12月时
       begin 
         set @i=@i+89  --如果为12月时+89转为+1年
       end 
       else 
       set @i=@i+1 
       set @j=@j+1 
    end   --c1,c2,c3应该分别为第1个月,第2个月,第3个月
  end 
end 
else --@m1 <=9  以下代码为处理月份<=9月的情况,所得的c1,c2,c3与上面情况相同
begin 
  if (@m2-@m1+1>3) or (@m2 <@m1) 
     return 
  else 
  begin  
    set @j=1 
    set @n1=@y1*100+@m1   
    set @n2=@y2*100+@m2   
    set @i=@n1 
--select @n1,@n2 
    while @i <= @n2 
    begin 
       set @ym=convert(varchar(6),@i) 
       if @j=1 
       set @c1=@ym 
       else 
       if @j=2  
       set @c2=@ym 
       else 
       set @c3=@ym   
       set @j=@j+1 
       set @i=@i+1 
    end   
  end