/*用遞迴處理樹型結構(表結構)遞迴求城市,從小到大的,或從大到小。*//*等依次類推得分類樹結構我想寫一個函數 傳入部門ID號後 馬上得到相應的 部門結構 如輸入8得到的是市場部-東南市場-上海市輸入9得到的是市場部-西北市場-北京市輸入6得到的是市場部-西北市場 輸入3得到的是市場部 輸入1得到的是所有部門*/--建立測試環境create table TableA(deptID int,deptName nvarchar(100),parentID int)insert into TableAselect 1,'所有部門',0 union allselect 2,'財務部', 1 union allselect 3,'市場部', 1 union allselect 4,'倉庫管理',1 union allselect 5,'東北市場',3 union allselect 6,'西北市場',3 union allselect 7,'東南市場',3 union allselect 8,'上海市', 7 union allselect 9,'北京市', 6 --建立函數if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AllDept]') and xtype in (N'FN', N'IF', N'TF'))drop function [dbo].[AllDept]GO CREATE function AllDept(@iDeptID int)returns nvarchar(1000)asbegin declare @vReturnValue nvarchar(1000) ,@iParentID int ,@vCurrentDeptName nvarchar(200) select @vReturnValue='' ,@vCurrentDeptName='' if(exists(select top 1 0 from TableA where DeptID=@iDeptID and parentID=0)) begin select @vReturnValue =@vReturnValue+deptName+'-' from TableA where parentID<>0 return (@vReturnValue) end if(exists(select top 1 0 from TableA where DeptID=@iDeptID and parentID=1)) begin select @vReturnValue=@vReturnValue+deptName from TableA where DeptID=@iDeptID and parentID=1 --return (@vReturnValue) --set @vReturnValue=@vReturnValue+dbo.AllDept(@iParentID) end else begin select @iParentID=parentID ,@vCurrentDeptName=deptName from TableA where DeptID=@iDeptID set @vReturnValue=@vReturnValue+@vCurrentDeptName+'-'+dbo.AllDept(@iParentID) --return (@vReturnValue) end return (@vReturnValue)end GOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GO select *,dbo.AllDept(deptid) AllDeptName from tableA select * from tableA--顯示結果deptId deptName AllDeptName1 所有部門 0 財務部-市場部-倉庫管理-東北市場-西北市場-東南市場-上海市-北京市-2 財務部 1 財務部3 市場部 1 市場部4 倉庫管理 1 倉庫管理5 東北市場 3 東北市場-市場部6 西北市場 3 西北市場-市場部7 東南市場 3 東南市場-市場部8 上海市 7 上海市-東南市場-市場部9 北京市 6 北京市-西北市場-市場部--刪除測試環境drop table tableAdrop table dbo.AllDept