# 在SQL SERVER 2005中實現素數計算

我將提出一個挑戰，誰能用SQLSEERVER提出計算素數最好的方法，我用了一個新的特點CTE和某些TSQL實現，但均不理想，前者（CTE）有限制，而後者（TSQL）產生一百萬個素數用了7分種你可以乾的更好嗎？這兒是我的一些程式碼片段落

（TSQL實現）

`set nocount ondeclare @prime table (prime int not null primary key)--insert into @prime values (2)--insert into @prime values (3)--insert into @prime values (5)--insert into @prime values (7)--insert into @prime values (11)declare @number int, @pc intset @number = 13set @pc = 1while @pc < 1000000beginif not exists (select 1 from @prime where @number % prime = 0 and prime < sqrt(@number) )begininsert into @prime select @numberset @pc = @pc +1endset @number = @number+ case when @number %2 = 1 then 2when @number %3 = 2 then 2when @number %5 = 4 then 2when @number %7 = 6 then 2when @number %11 = 10 then 2else 1 endendselect @pc`

和

（CTE實現）

`with seqas( select 13 numberunion allselect s.number+ case when s.number %2 = 1 then 2when s.number %3 = 2 then 2when s.number %5 = 4 then 2when s.number %7 = 6 then 2when s.number %11 = 10 then 2else 1 endfrom seq swhere number < 32767), prime as (select s.numberfrom seq swhere not exists ( select 1 from seq s2 where s2.number < s.number and (s.number) % s2.number = 0))select *from primeoption (MAXRECURSION 32767)`

## Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD