实现杨辉三角

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

CREATE proc #pr_YangHui
@c int
as
 /*    SQL实现显示杨辉三角    */
 /* 版本:   1.0              */
 /* 作者: Haiwer             */
 /* 版权所有                  */
 /* 2006.05.10               */
set nocount on
if @c<2 return        --两层以下就不排了
declare @i int
declare @j int
declare @sql varchar(8000)
declare @sql1 varchar(8000)
declare @sql2 varchar(8000)
create table #(id int IDENTITY(1,1),a50000 bigint)
insert #(a50000) values (1)   --第一层
set @i=2
while @i<=@c
begin
 --为了实现动态层,只好动态修改临时表结构
 set @sql='alter table # add a'+cast(50000+@i-1 as varchar(10))+' bigint,a'+cast(50000-@i+1 as varchar(10))+' bigint'  
 exec (@sql)
 set @sql1=''
 set @sql2=''
 set @j=@i-1
 while @j>=0
 begin
  --这里判断有点乱
  if @j=0
   set @sql1=@sql1+',a'+cast(50000-@j as varchar(10))
  else
   set @sql1=@sql1+',a'+cast(50000-@j as varchar(10))+',a'+cast(50000+@j as varchar(10))
  if @j=@i-1
   set @sql2=@sql2+',1,1'
  else
   if @j=0
    set @sql2=@sql2+',a'+cast(50000-@j-1 as varchar(10))+'+a'+cast(50000-@j+1 as varchar(10))
   else
    set @sql2=@sql2+',a'+cast(50000-@j-1 as varchar(10))+'+a'+cast(50000-@j+1 as varchar(10))+',a'+cast(50000+@j-1 as varchar(10))+'+a'+cast(50000+@j+1 as varchar(10))
  
  set @j=@j-2
 end
 --去掉多余的逗号
 set @sql1=right(@sql1,len(@sql1)-1)
 set @sql2=right(@sql2,len(@sql2)-1)
 set @sql=cast(@i-1 as varchar(10))
 exec('insert #('+@sql1+') select '+@sql2+' from # where id='+@sql)
 set @i=@i+1
end

set @i=50000-@c+1
set @j=50000+@c-1
set @sql=''
--去最长的数据,就是为了节省显示空间
select @sql1=CAST(len(cast(max(a50000) as varchar(50)))+1 AS VARCHAR(10)) from #
while @i<=@j
begin
 set @sql=@sql+',isnull(cast(a'+cast(@i as varchar(10))+' as varchar('+@sql1+')),'''')'
 set @i=@i+1
end
exec ('select id'+@sql+' from # order by id')
drop table #

GO
 
--调用
exec #pr_YangHui 8