现在的位置: 首页 > 综合 > 正文

SQL实现杨辉三角

2013年05月29日 ⁄ 综合 ⁄ 共 1325字 ⁄ 字号 评论关闭

呵呵,昨天看了海老师的博客,今天也自己写了一个:

  1. go
  2. create proc pr_YangHui
  3.     @n int  --杨辉三角的层数,1~67
  4. as
  5.  /*    SQL实现显示杨辉三角    */
  6.  /* 版本:   1.0              */
  7.  /* 作者: dobear             */
  8.  /* 版权所有                  */
  9.  /* 2008.11.04               */
  10. begin
  11.     set nocount on
  12.     if @n<1 or @n>67 
  13.         return
  14.     declare @t table(nid int identity(1,1), val bigint) --存储杨辉三角中的数字
  15.     insert @t select top 80 1 from sysobjects a, sysobjects b
  16.     declare @i int, @str varchar(4000), @nWidth int, @cSpace varchar(20)
  17.     
  18.     --计算数字的最大宽度,以便控制数字前面显示的空格
  19.     set @i=1
  20.     while @i<=@n
  21.     begin
  22.         update a set val=a.val+b.val
  23.         from @t a join @t b on a.nid=b.nid+1 where a.nid<@i         
  24.         set @i=@i+1     
  25.     end     
  26.     select @nWidth = len(max(val))+1 from @t    
  27.     update @t set val=1 where nid<@i
  28.     select @nWidth = @nWidth + @nWidth%2, @cSpace=space(@nWidth)
  29.     --打印杨辉三角
  30.     set @i=1
  31.     while @i<=@n
  32.     begin
  33.         update a set val=a.val+b.val
  34.         from @t a join @t b on a.nid=b.nid+1 where a.nid<@i
  35.         set @str=''
  36.         select @str=@str+right(@cSpace+cast(val as varchar), @nWidth) from @t where nid<=@i
  37.         print space((@n-@i)*@nWidth/2)+@str
  38.         set @i=@i+1     
  39.     end 
  40. end
  41. go
  42. exec pr_YangHui 6
  43. /*
  44.              1
  45.            1   1
  46.          1   2   1
  47.        1   3   3   1
  48.      1   4   6   4   1
  49.    1   5  10  10   5   1
  50. */
  51. --drop proc pr_YangHui

抱歉!评论已关闭.