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
原文地址:https://www.cnblogs.com/wenjl520/p/1326633.html