繁体   English   中英

SQL查询列出所有父项

[英]SQL Query to list all Parent Items

我正在使用下表:

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

给定一个GroupID ,我如何列出所有父组直到根以降序排列,其中根组是ParentID等于0的任何组?

例如

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

这使用了递归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.直接

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM