[英]Self recursive SQL Server database table to create a tree structure, create model for this , and using this data in Devexpress
我有location
和employee
數據庫表。 我想顯示所有位置(從根位置到所有子位置)和這些位置中存在的項目。 我決定使用 Devexpress 報告來創建包含此信息的報告。 該項目使用 ASP.NET MVC 實現。 我需要幫助,你能幫我完成這個項目嗎?
我在 SQL 服務器中的Location
表如下所示:
和我的Employee
表
我想在這樣的報告中創建一個結果:
Apple
Apple America
Apple New York
...
Name1 Surname1 gender1 profession1 ...
Name2 Surname2 gender2 profession2 ...
Apple Boston
Name3 Surname3 gender3 profession3 ...
我應該創建什么 model 來實現這個結構,你能給我一些建議嗎,我以錯誤的方式檢索數據。
要獲取遞歸數據,您可以使用遞歸公用表表達式,如下所示:
DECLARE @DataSource TABLE
(
[parentid] INT
,[childid] INT
,[name] VARCHAR(16)
);
INSERT INTO @DataSource ([parentid], [childid], [name])
VALUES (NULL, 10, 'parent A')
,(10, 11, 'child A1')
,(10, 12, 'child A2')
,(NULL, 13, 'parent B')
,(13, 14, 'sub-parent B1')
,(13, 15, 'sub-parent B2')
,(14, 16, 'child B2 - C1')
,(14, 17, 'child B2 - C2');
WITH RecursiveDataSource AS
(
SELECT *
,1 AS [Level]
,ROW_NUMBER() OVER (ORDER BY(SELECT 1)) AS [FamilyID]
FROM @DataSource
WHERE [parentid] IS NULL
UNION ALL
SELECT DS.*
,RDS.[Level] + 1
,RDS.[FamilyID]
FROM RecursiveDataSource RDS
INNER JOIN @DataSource DS
ON RDS.[childid] = DS.[parentid]
)
SELECT *
FROM RecursiveDataSource
ORDER BY [FamilyID]
,[Level];
然后使用這些列,您可以以所需的方式激活數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.