从递归函数返回可伸缩值

时间:2013-10-15 11:27:11

标签: sql sql-server

我有这个递归功能。 对于分层值表,我收到一个id,并希望将该id的父级返回到某个级别(unity_id)

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
)

但是我需要返回一个int而不是一个表,所以我试过这个。 我把“RETURNS int”而不是“RETURNS table” 我正在选择我想要的属性(它是一个int)

CREATE FUNCTION getObs
(
    @obs int
)
RETURNS int
as
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 r.OBS_Id 
    FROM ret2 r
    WHERE unity_id = 7
)

感谢您的帮助,我是SQL和函数的新手。

3 个答案:

答案 0 :(得分:0)

更改函数以显式返回int,而不是从表中转换它。

as
begin
    declare @ret int

    ;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 @ret = r.OBS_Id 
    FROM ret2 r
    WHERE unity_id = 7

    return @ret
end

答案 1 :(得分:0)

您可以使用以下代码声明变量,为其赋值并返回它。

CREATE FUNCTION getObs
(
    @obs int
)
RETURNS int
as
begin
    declare @return int

        ;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 @return = r.OBS_Id 
        FROM ret2 r
        WHERE unity_id = 7

        return @return

end

答案 2 :(得分:0)

在你还没有返回之前的CTE之前,如果你想返回一个int,你只需将值放在RETURN命令之后。

CREATE FUNCTION getObs
(
    @obs int
)
RETURNS int
as
BEGIN
    DECLARE @value int

    ;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 @value = r.OBS_Id 
    FROM ret2 r
    WHERE unity_id = 7

    RETURN @value -- return the int.
END