sql select parent child recursive in one field

我的未来我决定 提交于 2021-02-07 01:59:08

问题


I do not know how to select query recursive..

 id     idparent    jobNO
--------------------------------
  1         0         1
  2         1         2
  3         1         3
  4         0         4
  5         4         5
  6         4         6

how do the results like this With SqlServer

 id     idparent    jobNO   ListJob
----------------------------------------
  1         0         1        1
  2         1         2        1/2
  3         1         3        1/3
  4         0         4        4
  5         4         5        4/5
  6         5         6        4/5/6

回答1:


You need to use a Recursive Common Table Expression.

There are many useful articles online.

Useful Links

Simple Talk: SQL Server CTE Basics

blog.sqlauthority: Recursive CTE

Here is a solution to your question:

   CREATE TABLE #TEST
    (
        id int not null,
        idparent int not null,
        jobno int not null
    );

    INSERT INTO #Test VALUES 
    (1,0,1),
    (2,1,2),
    (3,1,3),
    (4,0,4),
    (5,4,5),
    (6,5,6);

    WITH CTE AS (
-- This is end of the recursion: Select items with no parent
        SELECT id, idparent, jobno, CONVERT(VARCHAR(MAX),jobno) AS ListJob
        FROM #Test
        WHERE idParent = 0
    UNION ALL
-- This is the recursive part: It joins to CTE
        SELECT t.id, t.idparent, t.jobno,  c.ListJob + '/' + CONVERT(VARCHAR(MAX),t.jobno) AS ListJob
        FROM #Test t
        INNER JOIN CTE c ON t.idParent = c.id
    )
    SELECT * FROM CTE
    ORDER BY id;


来源:https://stackoverflow.com/questions/37679357/sql-select-parent-child-recursive-in-one-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!