SQL实现显示杨辉三角(转载)

 

  • create proc pr_YangHui
  •     @n int  --杨辉三角的层数,1~67
  • as
  •  /*    SQL实现显示杨辉三角    */
  • begin
  •     set nocount on
  •     if @n<1 or @n>67 
  •         return
  •     declare @t table(nid int identity(1,1), val bigint) --存储杨辉三角中的数字
  •     insert @t select top 80 1 from sysobjects a, sysobjects b
  •     declare @i int, @str varchar(4000), @nWidth int, @cSpace varchar(20)
  •     
  •     --计算数字的最大宽度,以便控制数字前面显示的空格
  •     set @i=1
  •     while @i<=@n
  •     begin
  •         update a set val=a.val+b.val
  •         from @t a join @t b on a.nid=b.nid+1 where a.nid<@i         
  •         set @i=@i+1     
  •     end     
  •     select @nWidth = len(max(val))+1 from @t    
  •     update @t set val=1 where nid<@i
  •     select @nWidth = @nWidth + @nWidth%2, @cSpace=space(@nWidth)
  •     --打印杨辉三角
  •     set @i=1
  •     while @i<=@n
  •     begin
  •         update a set val=a.val+b.val
  •         from @t a join @t b on a.nid=b.nid+1 where a.nid<@i
  •         set @str=''
  •         select @str=@str+right(@cSpace+cast(val as varchar), @nWidth) from @t where nid<=@i
  •         print space((@n-@i)*@nWidth/2)+@str
  •         set @i=@i+1     
  •     end 
  • end
  • go
  • exec pr_YangHui 6
  • /*
  •              1
  •            1   1
  •          1   2   1
  •        1   3   3   1
  •      1   4   6   4   1
  •    1   5  10  10   5   1
  • */
  • --drop proc pr_YangHui
  • posted @   温景良(Jason)  Views(963)  Comments(0Edit  收藏  举报
    编辑推荐:
    · 如何编写易于单元测试的代码
    · 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
    · .NET Core 中如何实现缓存的预热?
    · 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
    · AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
    阅读排行:
    · 周边上新:园子的第一款马克杯温暖上架
    · Open-Sora 2.0 重磅开源!
    · 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
    · Ollama——大语言模型本地部署的极速利器
    · DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
    点击右上角即可分享
    微信分享提示