樹結構表遞歸查詢在ORACLE和MSSQL中的實現方法 [續]
上文中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表中的記錄是動態增加的,如果寫靜態的值,這個循環就會變成一個死循環.
浙公網安備 33010602011771號