Use tempdb;
Go
-- I use stored procedures and temporary tables for writing. I mainly want to output the result of the last SELECT statement and arrange it in the desired triangle shape.
-- Due to restrictions on bigint data, up to 67 layers can be displayed.
Create proc pr_yanghui
@ C int
As
/* SQL implementation display Yang Hui triangle */
/* Version: 1.0 */
/* Author: haiwer */
/* Copyright */
/* 2006.05.10 */
Set nocount on
If @ C <2 Return -- No rows below two layers
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) -- First Layer
Set @ I = 2
While @ I <= @ C
Begin
-- In order to implement the dynamic layer, we had to modify the temporary table structure dynamically.
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
-- This is a bit messy.
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
-- Remove unnecessary commas
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 =''
-- Remove the longest data to save the display space
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
-- Call
Pr_yanghui 8
-- Result
-- ID
-------------------------------------------------------------------------
-- 1 1
-- 2 1 1
-- 3 1 2 1
-- 4 1 3 3 1
-- 5 1 4 6 4 1
-- 6 1 5 10 10 5 1
-- 7 1 6 15 20 15 6 1
-- 8 1 7 21 35 35 21 7 1