用遞迴處理樹型結構(表結構)

來源:互聯網
上載者:User
/*用遞迴處理樹型結構(表結構)遞迴求城市,從小到大的,或從大到小。*//*等依次類推得分類樹結構我想寫一個函數 傳入部門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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.