我必须遵循SQL Server 2008 R2中的数据。SQLFiddle
架构:
创建表[dbo]。[ICFilters]( [ICFilterID] [int] IDENTITY(1,1)NOT NULL, [ParentID] [int] NOT NULL默认值0, [FilterDesc] [varchar](50)NOT NULL, [Active] [tinyint] NOT NULL默认值1, 约束[PK_ICFilters]主键 ([ICFilterID] ASC)与 PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS =开启 )在[PRIMARY]上 )在[PRIMARY]上 插入[dbo]。[ICFilters](ParentID,FilterDesc,活动) 价值观 (0,“产品类型”,1), (1,'ProdSubType_1',1), (1,'ProdSubType_2',1), (1,'ProdSubType_3',1), (1,'ProdSubType_4',1), (2,'PST_1.1',1), (2,'PST_1.2',1), (2,'PST_1.3',1), (2,'PST_1.4',1), (2,'PST_1.5',1), (2,'PST_1.6',1), (2,'PST_1.7',0), (3,'PST_2.1',1), (3,'PST_2.2',0), (3,'PST_2.3',1), (3,'PST_2.4',1), (14,'PST_2.2.1',1), (14,'PST_2.2.2',1), (14,'PST_2.2.3',1), (3,'PST_2.8',1)
表:
| ICFILTERID | 父母 FILTERDESC | 活动| -------------------------------------------------- | 1 | 0 | 产品种类 1 | | 2 | 1 | ProdSubType_1 | 1 | | 3 | 1 | ProdSubType_2 | 1 | | 4 | 1 | ProdSubType_3 | 1 | | 5 | 1 | ProdSubType_4 | 1 | | 6 | 2 | PST_1.1 | 1 | | 7 | 2 | PST_1.2 | 1 | | 8 | 2 | PST_1.3 | 1 | | 9 | 2 | PST_1.4 | 1 | | 10 | 2 | PST_1.5 | 1 | | 11 | 2 | PST_1.6 | 1 | | 12 | 2 | PST_1.7 | 0 | | 13 | 3 | PST_2.1 | 1 | | 14 | 3 | PST_2.2 | 0 | | 15 | 3 | PST_2.3 | 1 | | 16 | 3 | PST_2.4 | 1 | | 17 | 14 | PST_2.2.1 | 1 | | 18 | 14 | PST_2.2.2 | 1 | | 19 | 14 | PST_2.2.3 | 1 | | 20 | 3 | PST_2.8 | 1 |
每行都有其父代的ID和根的ID parentid = 0
。该FilterDesc
s为刚刚样本的描述,所以我不能尝试解析那些排序。
问题
是否可以以树状方式选择所有行?如果是这样,怎么办?当我说“树状”时,我的意思是递归地选择父级,然后选择其所有子级,然后依次选择每个父级的所有子级,依此类推。深度优先的树遍历。
我和我的朋友们已经尝试过了,但我们仍未找到可行的解决方案,但会继续尝试。我对sql还是很陌生,所以也许可以很容易地做到这一点,而我只是使事情变得比必要的难。
示例(所需)输出:
| ICFILTERID | 父母 FILTERDESC | 活动| -------------------------------------------------- | 1 | 0 | 产品种类 1 | | 2 | 1 | ProdSubType_1 | 1 | | 6 | 2 | PST_1.1 | 1 | | 7 | 2 | PST_1.2 | 1 | | 8 | 2 | PST_1.3 | 1 | | 9 | 2 | PST_1.4 | 1 | | 10 | 2 | PST_1.5 | 1 | | 11 | 2 | PST_1.6 | 1 | | 12 | 2 | PST_1.7 | 0 | | 3 | 1 | ProdSubType_2 | 1 | | 13 | 3 | PST_2.1 | 1 | | 14 | 3 | PST_2.2 | 0 | | 17 | 14 | PST_2.2.1 | 1 | | 18 | 14 | PST_2.2.2 | 1 | | 19 | 14 | PST_2.2.3 | 1 | | 15 | 3 | PST_2.3 | 1 | | 16 | 3 | PST_2.4 | 1 | | 20 | 3 | PST_2.8 | 1 | | 4 | 1 | ProdSubType_3 | 1 | | 5 | 1 | ProdSubType_4 | 1 |