日韩天天综合网_野战两个奶头被亲到高潮_亚洲日韩欧美精品综合_av女人天堂污污污_视频一区**字幕无弹窗_国产亚洲欧美小视频_国内性爱精品在线免费视频_国产一级电影在线播放_日韩欧美内地福利_亚洲一二三不卡片区

通過SQL繪制楊輝三角的實(shí)現(xiàn)方法介紹_Mssql數(shù)據(jù)庫教程

編輯Tag賺U幣

推薦:關(guān)于重新組織和重新生成索引sp_RefreshIndex的介紹
本篇文章小編為大家介紹,關(guān)于重新組織和重新生成索引sp_RefreshIndex的介紹。需要的朋友參考下

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

以下是完整的SQL代碼

復(fù)制代碼 代碼如下:www.hl5o.cn

use tempdb
go
set nocount on
declare @rows int=10, --行數(shù),根據(jù)實(shí)際來控制
@x int=1,@y int=1,@sql nvarchar(max),@cols int

/*
根據(jù)楊輝三角的組合數(shù)計(jì)算方法:C(n,m)=n!/[m!(n-m)!]進(jìn)行繪制
參照: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)


(【注】:當(dāng)前腳本在SQL Server 2012上測試通過)

效果圖:



這方法雖然沒有借助臨時(shí)表,也有一個(gè)最大的不足就是不能設(shè)置太多行,因?yàn)樵诠剑–(n,m)=n!/[m!(n-m)!])中有n! 和m! 算式,設(shè)置行數(shù)太多會導(dǎo)致階乘數(shù)據(jù)太大,發(fā)生數(shù)據(jù)類型轉(zhuǎn)換溢出。有時(shí)間再想辦法看能否從表示式中"/"除位置進(jìn)行優(yōu)化

分享:SqlServer獲取存儲過程返回值的實(shí)例
SqlServer獲取存儲過程返回值的實(shí)例,需要的朋友可以參考一下

來源:模板無憂//所屬分類:Mssql數(shù)據(jù)庫教程/更新時(shí)間:2013-04-23
相關(guān)Mssql數(shù)據(jù)庫教程