0

I've got this recursive function. For a table of hierarchical values, I receive a id and want to return the parent of that id for a certain level (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
)

But I need to return an int instead of a table, so I've tried this. I've put "RETURNS int" and not "RETURNS table" I'm selecting the property I want (it's an 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
)

Thank you for any help, I'm new to SQL and functions.

4

3 回答 3

0

Change the function to explicitly return the int, rather than casting it from a table.

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
于 2013-10-15T11:29:14.690 回答
0

You can use the code below to declare a variable, assign a value to it and return it.

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
于 2013-10-15T11:31:41.400 回答
0

Before you were still returning the CTE you had before, if you want to return an int you just simply place the value after the RETURN command.

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
于 2013-10-15T11:33:36.467 回答