有一个id和fid字段 fid是记录上1级的id号我想通过一句话根据id查询出包括自己的所有子id行.          id fid
比如数据是2   1
          3   2
          4   3
          5   3
          6   5
查询2 就返回 2 3 4 5 6行

解决方案 »

  1.   

    create table tb([user_group_id] int,[per_group_id] int,[user_group_name] varchar(10))
    insert tb
    select 1,0,'总管理员' union all
    select 2,1,'一级管理员' union all
    select 3,2,'二级管理员' union all
    select 4,3,'三级管理员' union all
    select 8,4,'四级管理员' union all
    select 10,8,'五级管理员'--2000
    ---创建函数
    CREATE FUNCTION f_Cid(@name varchar(10))
    RETURNS @t TABLE(ID varchar(10),Level int)
    AS
    BEGIN
    DECLARE @Level int,@id int
    SET @Level=1
    set @id=(select [per_group_id] from tb where [user_group_name]=@name )
    INSERT @t SELECT @ID,@Level
    WHILE @@ROWCOUNT>0
    BEGIN
    SET @Level=@Level+1
    INSERT @t SELECT a.[user_group_id],@Level
    FROM tb a,@t b
    WHERE a.[per_group_id]=b.id
    AND b.Level=@Level-1
    END
    RETURN
    END
    GO--调用函数查询二级管理员及其所有子节点
    SELECT a.*
    FROM tb a,f_Cid('二级管理员') b
    WHERE a.[per_group_id]=b.id/*
    user_group_id per_group_id user_group_name
    ------------- ------------ ---------------
    3 2 二级管理员
    4 3 三级管理员
    8 4 四级管理员
    10 8 五级管理员(4 行受影响)2000是要用函数的,
    05的可以使用CTE
      

  2.   

    哦。.那没办法了。..select aid from test where aid like '%'+id+'%'
    我想根据id来模糊查询aid..怎么写出错..应该怎么写的。将 varchar 值 '%' 转换为数据类型为 int 的列时发生语法错误。
      

  3.   

    select aid from test where aid like '%'+LTRIM(id)+'%'
    我想根据id来模糊查询aid..怎么写出错..应该怎么写的。这样模糊查询是什么意思,不懂,2000的请参数函数吧,
      

  4.   

    2000的一楼可行下面是2005的递归实现法---- 查询'河北省'下的所有市县
    --利用cte实现递归
    --> 测试数据:[tb]DECLARE  @tb Table([id] int,[col1] varchar(8),[col2] int)
    insert @tb
    select 1,'河北省',0 union all
    select 2,'邢台市',1 union all
    select 3,'石家庄市',1 union all
    select 4,'张家口市',1 union all
    select 5,'南宫',2 union all
    select 6,'坝上',4 union all
    select 7,'任县',2 union all
    select 8,'清河',2 union all
    select 9,'河南省',0 union all
    select 10,'新乡市',9 union all
    select 11,'aaa',10 union all
    select 12,'bbb',10;with t as(
    select * from @tb where col1='河北省'
    union all
    select a.* from @tb a  ,t where a.col2=t.id)
    select * from t
      

  5.   

    递归查询,这里有个现存的:
    http://www.cnblogs.com/sweting/archive/2009/06/08/1498483.html