读书人

这个存储过程是什么意思?该怎么解决

发布时间: 2012-01-23 21:57:28 作者: rapoo

这个存储过程是什么意思?
这段的存储过程的代码是什么意思 请大家指点一下
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
return
else
begin
set @j=1
set @n1=@y1*100+@m1
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
begin
set @i=@i+89
end
else
set @i=@i+1
set @j=@j+1
end

end
end
else --@m1<=9
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


[解决办法]
加上了注释,
处理结果应该是取日期d1到d2间的3个月,分别赋给c1,c2,c3
如d1='2008-1-1',d2='2008-4-1',即得出c1='200801',c2='200802',c3='200803'
如d1='2007-12-1',d2='2008-2-1' 可得出c1='200712',c2='200801',c3='200802'

SQL code
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 

读书人网 >SQL Server

热点推荐