2016-07-30 58 views
0

我用下表工作:SQL查詢,列出所有父件

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

給定一個GroupID,我如何列出所有的父組,直到根降序排列,其中,根羣是任何集團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 

回答

-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) 
+0

請看新的例子。無論如何,這個要求已經明確說明了。 – 2016-07-30 20:10:11

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(); 
     } 
    } 

}