2013-10-15 53 views
2

我想創建一個函數來返回遞歸值,但我得到一個語法錯誤。用於返回遞歸值的SQL函數

CREATE FUNCTION getObs 
(
    @obs int 
) 
RETURNS 
WITH ret2 AS(
    SELECT * 
    FROM OBS 
    WHERE OBS_Id = @obs 
    UNION ALL 
    SELECT t.* 
    FROM OBS as t INNER JOIN 
     ret2 r ON t.OBS_Id = r.UnitId 
    ) 
SELECT * 
FROM ret2 r 
WHERE unity_id = 7 
+0

什麼是錯誤? – Szymon

回答

3

RETURNS指定函數的返回類型,在那之後你必須定義函數體,這樣的:

CREATE FUNCTION getObs 
(
    @obs int 
) 
RETURNS table -- <-- returns table so it's a table function 
as 
return -- <- here's actual return 
(
    WITH ret2 AS(
     SELECT * 
     FROM OBS 
     WHERE OBS_Id = @obs 
     UNION ALL 
     SELECT t.* 
     FROM OBS as t INNER JOIN 
      ret2 r ON t.OBS_Id = r.UnitId 

     ) 
    SELECT * 
    FROM ret2 r 
    WHERE unity_id = 7 
) 

這裏是一個例子 - sql fiddle demo

0

RETURNS的一部分語句沒有指定它將返回的內容。