2012-10-17 126 views
8

如何從一個while循環創建SQL Server的CTE
我的循環這樣創建while循環與CTE

declare @ind as int 
    declare @code as nvarchar 
    set @ind = 0 
    while @ind < 884 
    begin 
    select @ind = @ind + 1 
    --here execute Procedure 
     --and set return value to variable 
    set @code = cast (@ind as nvarchar) 
    end 
+0

是一個絕對需要的遞歸cte? - 這是一個結構,當我嘗試運行總計或者像數據結構一樣走在一棵樹上時,我會用一個簡單循環'while while' is spot on。 – whytheq

+0

你需要結果作爲表或單個字符串? – TechDo

+0

您不能將存儲過程作爲查詢的一部分調用* - 您需要將存儲過程的定義擴展到此查詢中 - 是您想要執行的操作嗎? –

回答

3

如果您需要表:

;WITH Sec(Number) AS 
(
    SELECT 0 AS Number 
    UNION ALL 
    SELECT Number + 1 
    FROM Sec 
    WHERE Number < 884 
) 

SELECT * FROM Sec 
OPTION(MAXRECURSION 0) 

如果您需要一個字符串:

;WITH Sec(Number) AS 
(
    SELECT 0 AS Number 
    UNION ALL 
    SELECT Number + 1 
    FROM Sec 
    WHERE Number < 884 
) 

SELECT STUFF(a.[Str], 1, 1, '') 
FROM 
(
    SELECT (SELECT ',' + CAST(Number AS NVARCHAR(3)) 
    FROM Sec 
    FOR XML PATH(''), TYPE 
    ).value('.','varchar(max)') AS [Str] 
) AS a 
OPTION(MAXRECURSION 0) 
5

下面的查詢從0到884選擇的值:

;WITH T(Num)AS 
(
    SELECT 0 
    UNION ALL 
    SELECT Num+1 FROM T WHERE T.Num < 884 
)SELECT Num FROM T 
OPTION (MAXRECURSION 0);