(如何)我可以在表值函数中放置一个带有sql的查询吗?

时间:2014-05-29 18:46:38

标签: sql sql-server-2008

我想将以下查询作为表值函数的返回。

;with org as (
   select ID
   from ORG_UNIT
   where id = @ID_ORG_UNIT
   union all
   select PARENT_ID
   from ORG_UNIT c
     join org p on p.ID = c.id
) 
select * from org 

我已经尝试过创建这样一个函数,但我现在绝望地使用存储过程......

是否可以创建一个函数来返回此结果?

1 个答案:

答案 0 :(得分:1)

create function test_func(@ID_ORG_UNIT int)
returns table
as
return (
  with org as (
     select ID
     from ORG_UNIT
     where id = @ID_ORG_UNIT
     union all
     select PARENT_ID
     from ORG_UNIT c
       join org p on p.ID = c.id
  ) 
  select * from org   
);

SQLFiddle