天天看點

T-Sql ,自定義函數,傳回遞歸結果集

寫程式是總是用到父子關系的資料,通過給定節點得到其子節點的記錄,寫視圖但是不支援傳入參數。
那就用 自定義函數來完成這個需求吧!
1.建立視圖
create Function myFunc(@id Int)
 Returns @tab table (id int,ParentId int,[Level] int,TName nvarchar(50))
 As
  begin
  
    --DECLARE @typeId int;
    --set @typeId =6;
  with cte as
  (
   select * from  tab where id= @id
   union all 
   select a.* from tab a, cte b 
   where a.parentid = b.id
  )
  insert @tab select id ,ParentId,[Level],TName from cte;
  return
 End 
2.表值函數調用
select * from  dbo.myFunc(6)