通過SQL繪制楊輝三角


無意中在csdn上看到一帖有關繪制楊輝三角的sql表達式,感覺很有意思。后來自己想下不借助臨時表,根據楊輝三角的組合數計算方法C(n,m)=n!/[m!(n-m)!],進行繪制。

以下是完整的SQL代碼:

use tempdb
go
set nocount on
declare @rows int=10, --行數,根據實際來控制
        @x int=1,@y int=1,@sql nvarchar(max),@cols int
 
/*
根據楊輝三角的組合數計算方法:C(n,m)=n!/[m!(n-m)!]進行繪制
參照:http://baike.baidu.com/view/7804.htm
*/
 
set @cols=@rows*2-1
;with cte_n as
(
    select r from (select row_number() over(order by a.object_id) as r from sys.all_columns a ) x where r<=@rows*2
)
,cte_1 as(select n.r,b.data_lse
            from cte_n n
                cross apply(select 'select '+stuff((select ',rtrim('+isnull(F1.v+'/(('+F2.v+')*'+F3.v+')','''''') +') as '+quotename(isnull(nullif((m.r +(@rows-n.r)+(m.r-1)*1)%@cols,0),@cols))
                                from cte_n m
                                    outer apply(select stuff((select '*'+rtrim(i.r) from cte_n i where i.r<=isnull((nullif(n.r-1,0)),1) for xml path('')),1,1,'') as v
                                        ) F1
                                    outer apply(select stuff((select '*'+rtrim(i.r) from cte_n i where i.r<=isnull((nullif(m.r-1,0)),1) for xml path('')),1,1,'') as v
                                        ) F2
                                    outer apply(select stuff((select '*'+rtrim(i.r) from cte_n i where i.r<=isnull((nullif(n.r-m.r,0)),1) for xml path('')),1,1,'') as v
                                        ) F3
                                where m.r<@rows*2
                                order by isnull(nullif((m.r +(@rows-n.r)+(m.r-1)*1)%@cols,0),@cols) asc
                                for xml path('')                                    
                                ),1,1,'') as data_lse
                            )b
                where n.r <=@rows
            ) 

    select @sql=isnull(@sql+' union all ','')+data_lse from  cte_1
exec(@sql)

注】當前腳本在SQL Server 2012上測試通過

效果圖:

 

這方法雖然沒有借助臨時表,也有一個最大的不足就是不能設置太多行,因為在公式(C(n,m)=n!/[m!(n-m)!])中有n! 和m! 算式,設置行數太多會導致階乘數據太大,發生數據類型轉換溢出。有時間再想辦法看能否從表示式中"/"除位置進行優化。

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM