表结构id       parentid     name

解决方案 »

  1.   

    id       parentid     name
    0        NULL         SKSK
    1        NULL         KSKS
    2        0            KKKK
    3        1            LLLL
    4        3            KSKSKSRESULT ONLY 4
      

  2.   

    可以给 楼主启发,也可以到我的blog里,有关于这方面的介绍
    /*
    用递归处理树型结构(表结构)
    递归求城市,从小到大的,或从大到小。
    */
    /*
    等依次类推得目录树结构
    我想写一个函数 传入部门ID号后 马上得到相应的 部门结构 如
    输入8得到的是市场部-东南市场-上海市
    输入9得到的是市场部-西北市场-北京市
    输入6得到的是市场部-西北市场输入3得到的是市场部输入1得到的是所有部门
    */
    --建立测试环境
    create table TableA(deptID int,deptName nvarchar(100),parentID int)
    insert into TableA
    select 1,'所有部门',0 union all
    select 2,'财务部', 1 union all
    select 3,'市场部', 1 union all
    select 4,'仓库管理',1 union all
    select 5,'东北市场',3 union all
    select 6,'西北市场',3 union all
    select 7,'东南市场',3 union all
    select 8,'上海市', 7 union all
    select 9,'北京市', 6--建立函数
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AllDept]') and xtype in (N'FN', N'IF', N'TF'))
    drop function [dbo].[AllDept]
    GOCREATE function AllDept(@iDeptID int)
    returns nvarchar(1000)
    as
    begin
    declare @vReturnValue nvarchar(1000)
    ,@iParentID int
    ,@vCurrentDeptName nvarchar(200)
    select @vReturnValue=''
    ,@vCurrentDeptName=''
    if(exists(select top 1 0 from TableA where DeptID=@iDeptID and parentID=0))
    begin
    select @vReturnValue =@vReturnValue+deptName+'-'
    from TableA
    where parentID<>0
    return (@vReturnValue)
    end
    if(exists(select top 1 0 from TableA where DeptID=@iDeptID and parentID=1))
    begin
    select @vReturnValue=@vReturnValue+deptName 
    from TableA where DeptID=@iDeptID and parentID=1
    --return (@vReturnValue)
    --set @vReturnValue=@vReturnValue+dbo.AllDept(@iParentID)
    end
    else
    begin
    select @iParentID=parentID 
    ,@vCurrentDeptName=deptName
    from TableA 
    where DeptID=@iDeptID
    set @vReturnValue=@vReturnValue+@vCurrentDeptName+'-'+dbo.AllDept(@iParentID)
    --return (@vReturnValue)
    end
    return (@vReturnValue)
    endGO
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GOselect *,dbo.AllDept(deptid) AllDeptName from tableAselect * from tableA
    --显示结果
    deptId deptName AllDeptName
    1 所有部门 0 财务部-市场部-仓库管理-东北市场-西北市场-东南市场-上海市-北京市-
    2 财务部 1 财务部
    3 市场部 1 市场部
    4 仓库管理 1 仓库管理
    5 东北市场 3 东北市场-市场部
    6 西北市场 3 西北市场-市场部
    7 东南市场 3 东南市场-市场部
    8 上海市 7 上海市-东南市场-市场部
    9 北京市 6 北京市-西北市场-市场部
    --删除测试环境
    drop table tableA
    drop table dbo.AllDept
      

  3.   

    select *
    from tablename
    where id not in (select parentid from tablename)