簡體   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