【问题标题】:Self recursive SQL Server database table to create a tree structure, create model for this , and using this data in Devexpress自递归 SQL Server 数据库表创建树结构,为此创建模型,并在 Devexpress 中使用此数据
【发布时间】:2020-01-22 13:48:00
【问题描述】:

我有locationemployee 数据库表。我想显示所有位置(从根位置到所有子位置)和这些位置中存在的项目。我决定使用 Devexpress 报告来创建包含此信息的报告。这个项目是用 ASP.NET MVC 实现的。我需要帮助,你能帮我完成这个项目吗?

我在 SQL Server 中的Location 表如下所示:

  • 父代
  • childid
  • 姓名

还有我的Employee

  • 身份证
  • locationid(用于位置表)
  • 姓名
  • 性别
  • professionid(连接到另一个职业表:1:行政人员,2:技术人员......等)

我想在报告中创建这样的结果:

Apple
    Apple America
          Apple New York
               ...
                  Name1  Surname1    gender1  profession1   ... 
                  Name2  Surname2    gender2  profession2   ... 

           Apple Boston 
                  Name3  Surname3   gender3  profession3  ... 

我应该创建什么模型来实现这个结构你能给我一些建议吗,我以错误的方式检索数据。

【问题讨论】:

    标签: sql-server asp.net-mvc asp.net-core devexpress devexpress-mvc


    【解决方案1】:

    要获取递归数据,您可以像这样使用recursive common table expression

    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];
    

    然后使用这些列,您可以以所需的方式激活数据。

    【讨论】:

    • 谢谢@gotqn,经过一些调整,效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多