2016-11-20 128 views
1

使用SQL服務器,編寫一個while循環來計算和打印所有奇數非負整數的f(x)= 3x的函數值< = 25 (1,3,5,... 23,25)。SQL用while循環解決函數

這是我寫了到目前爲止

My Query

這是結果我得到

My Results

所以理論上我應該得到45640時@x = 25

我在這裏錯了什麼?

回答

1

你必須使用power功能類似下面的

Declare @SUMSQUARE Integer, @x Integer 
SET @X = 1 

WHILE (@X <= 25) 
BEGIN 

SELECT @SUMSQUARE = (3*power(@X,3))-(2*power(@X,2))+15 
PRINT @SUMSQUARE 
SET @X = @X + 2 

END 
1

您可以使用遞歸cte(而不是使用while循環)來生成所有奇數< = 25,然後將這些函數應用於這些數字。

with oddnums_cte as (select 1 num 
        union all 
        select num+2 from oddnums_cte where num < 25) 
select num, (3*power(num,3))-(2*power(num,2))+15 as function_value 
from oddnums_cte