zoukankan      html  css  js  c++  java
  • sql 根据关系表查找相应的父子类的数据

    Create Table A
    (ID Int,
     fatherID Int,
     Name Varchar(10)
    )
    Insert A Select 1,        NULL,       'tt'
    union   All Select 2,        1,          'aa'
    union   All Select 3,        1,          'bb'
    union   All Select 4,        2,          'cc'
    union   All Select 5,        2,          'gg'
    union   All Select 6,        4,          'yy'
    union   All Select 7,        4,          'jj'
    union   All Select 8,        7,           'll'
    union   All Select 9,        NULL,  'uu'
    union   All Select 10,       9,         'oo'
    GO
    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    GO
    create Function [dbo].[GetParent](@ID Int)
    Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
    As
    Begin
    Insert @Tree Select ID, fatherID, Name From A Where ID = @ID
    While @@Rowcount > 0
    Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.ID = B.fatherID And A.ID Not In (Select ID From @Tree)
    Return
    End

    --測試
    Select * From dbo.GetParent(4)


       本人博客的文章大部分来自网络转载,因为时间的关系,没有写明转载出处和作者。所以在些郑重的说明:文章只限交流,版权归作者。谢谢

  • 相关阅读:
    编译原理三大经典书籍
    c#之委托总结
    shell编程基础
    专家是什么?我真的想知道(转)
    linux sed
    判断一个脚本中的变量是否为空(转)
    JAVA Stack栈和Heap堆的区别(转)
    CMD获取当前目录的绝对路径 (转)
    RTP协议分析
    VS2010旗舰版安装图解
  • 原文地址:https://www.cnblogs.com/wzg0319/p/1819050.html
Copyright © 2011-2022 走看看