有一表iclass,数据如下
cID     cName             pID  cPath   cDepth   
1 第1        0 1 1
2 第2               1 1|2 2
3 第3               1 1|3 2
10 第4         0 10 1
11 第5               10 10|11 2
12 第6               10 10|12 2 想用一条sql语句,获取得到以下数据cID     cName             pID  cPath   cDepth   
1 第1        0 1 1
2 第2               1 1|2 2
3 第3               1 1|3 2
谢谢!

解决方案 »

  1.   

    SELECT TOP(3)* FROM iclass ORDER BY cID 
      

  2.   


    --猜一个
    --2005
    ;with t as
    (
    select * from iclass where cPath= 1
    union 
    select * from t,iclass i  where t.cPath=i.pID
    )
    select  * from t
      

  3.   

    可以用一句sql语句搞定不?我现在用
    SELECT * FROM movie_class where  cPath like  '1%'
    取出来的包含了第4,5,6了.我只需要第1,2,3
    同理:
    如果是
    SELECT * FROM movie_class where  cPath like  '10%'
    那应该取得第4,5,6关键是这里like  '1%'里,10,11,12就已经包含了.所以这样不行.
    想问下大家的方法.
      

  4.   


    --> 数据库版本:
    --> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
    --> 测试数据:[TB]
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TB]') 
    AND type in (N'U')) 
    DROP TABLE [TB]
    GO---->建表
    create table [TB]([cID] int,[cName] varchar(3),[pID] int,[cPath] varchar(5),[cDepth] int)
    insert [TB]
    select 1,'第1',0,'1',1 union all
    select 2,'第2',1,'1|2',2 union all
    select 3,'第3',1,'1|3',2 union all
    select 10,'第4',0,'10',1 union all
    select 11,'第5',10,'10|11',2 union all
    select 12,'第6',10,'10|12',2
    GO--> 查询结果
    select * from TB where [cPath]='10'
    union all
    SELECT  b.* FROM [TB] a inner join TB b
    on a.cPath=ltrim(b.pID)
    where 1=1 
    and a.[cPath]='10'
    --> 删除表格
    --DROP TABLE [TB]