樹結構表遞迴查詢在ORACLE和MSSQL中的實現方法 [續]

iSQlServer發表於2009-05-13

上文中MSSQL的資料是給定頂級物件,獲取頂級下面的所有樹,'

根據上面的寫法,我改出來根據樹枝列出根

ALTER function [dbo].[GetProjectTreeByProjectID1] (@id [uniqueidentifier])
returns @t table(
    [Guid] [uniqueidentifier],
    [ProjectName] [varchar](50),
    [Remark] [varchar](100),
    [ParentProject] [uniqueidentifier],
    [Depth] [int])
as
begin
    insert into @t select * from BI_Project where guid = @id
    while @@rowcount > 0
        insert @t
        select a.*
        from @t as b inner join BI_Project as a on b.parentproject = a.guid and a.guid not in(select guid from @t)
   return

end

 

本人最T-SQL並不是很在行,故在此解釋一下以備以後忘記時回憶, 如有錯誤懇請指正:

1.ALTER function [dbo].[GetProjectTreeByProjectID1] (@id [uniqueidentifier])   --function 說明是一個MSSQL 方法
returns @t table(      ---此處說明,此function返回的是一個下述表結構的一個表
    [Guid] [uniqueidentifier],
    [ProjectName] [varchar](50),
    [Remark] [varchar](100),
    [ParentProject] [uniqueidentifier],

    [Depth] [int])

 

2. insert into @t select * from BI_Project where guid = @id

先將當前物件插入到要返回的物件表@t中.

 

3. 此部分是關鍵部分,分解開來說明:

  while @@rowcount > 0

        insert @t
        select a.*

        from @t as b inner join BI_Project as a on b.parentproject = a.guid and a.guid not in(select guid from @t)

   3.1 @@rowcount --應該是MSSQL 內建變數,我們每次執行完SQL之後,MSSQL會自動設定@@rowcount的值為當前執行的結果的行數.

       3.2  from @t as b inner join BI_Project --將我們[當前:說明這個零時表中的資料實動態變化的]的零時表@t(也是執行完要返回的表哦)與原表[BI_Project]連線;

       3.3 條件說明:  on b.parentproject = a.guid and a.guid not in(select guid from @t) --B的parentproject與A.主鍵連線,並且A中排除已存在在B中的記錄.

       3.4 Q:  a.guid not in(select guid from @t) 這句可以寫具體的值嗎?

             A: 不可以, 因為@t表中的記錄是動態增加的,如果寫靜態的值,這個迴圈就會變成一個死迴圈.

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-594980/,如需轉載,請註明出處,否則將追究法律責任。

相關文章