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.