SQL Query列出所有父项

时间:2016-07-30 10:40:59

标签: c# sql sql-server

我正在使用下表:

CREATE TABLE Groups
(
    [GroupID] [uniqueidentifier] NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [ParentGroupID] [uniqueidentifier] NOT NULL CONSTRAINT 
);

给定GroupID,如何按root降序排列所有父组,其中root组是ParentID等于0的任何组?

E.g。

GroupID Name Parent
-------------------
1       One  0
2       Two  1
3       Three 2
4       Four  1
5       Five  3
6       Six   4
7       Seven 0

如果我指定5,那么它应该返回

3 Three
2 Two
1 One

2 个答案:

答案 0 :(得分:0)

这使用递归SQL C#只是从查询中获取结果并循环遍历它。

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string str = "my connection string";
        ReadData(str, "3");
    }

    private static void ReadData(string connectionString, string childId)
    {
        string queryString = @"WITH R (GroupID, Name, ParentID, level)
AS (
   select GroupID, Name, ParentGroupID, 1
   from Groups
   where GroupID = " + childId + @"
   union all
   select R.GroupID, R.Name, t.ParentGroupID, level + 1
   from R
   join Groups t
     on (R.ParentID = t.GroupID and t.ParentGroupID <> t.GroupID)
)
select R.GroupID, g.Name as ParentName, R.level, R.Name as GroupName, R.ParentID
from R
left join Groups g on (R.ParentID = g.GroupID)
where g.Name IS NOT NULL
order by R.groupID, R.level, R.ParentID";

        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
               var record = (IDataRecord) reader; 
               Console.WriteLine(String.Format("{0} {1}", record[0], record[1]));
            }

            reader.Close();
        }
    }

}

答案 1 :(得分:-1)

1。直接

with CTE as 
(
select '1' 'groupid','one' 'name','0' 'parent'
union all
select '2','two','1'
union all
select '3','three','2'
union all
select '4','four','3'
)
select * from cte where parent > 0 and parent <= (select parent from cte where groupid = '3')

2。使用参数

Declare @input  int = '3'
with CTE as 
(
select '1' 'groupid','one' 'name','0' 'parent'
union all
select '2','two','1'
union all
select '3','three','2'
union all
select '4','four','3'
)
select * from cte where parent > 0 and parent <= (select parent from cte where groupid = @input)