SQL SERVER級聯查詢及資料結構

來源:互聯網
上載者:User

create table tb(id varchar(3) , pid varchar(3) , name varchar(10))insert into tb values('001' null  '廣東省')insert into tb values('002' '001' '廣州市')insert into tb values('003' '001' '深圳市')insert into tb values('004' '002' '天河區')insert into tb values('005' '003' '羅湖區')insert into tb values('006' '003' '福田區')insert into tb values('007' '003' '寶安區')insert into tb values('008' '007' '西鄉鎮')insert into tb values('009' '007' '龍華鎮')insert into tb values('010' '007' '松崗鎮')go --查詢指定節點及其所有子節點的函數create function f_cid(@ID varchar(3)) returns @t_level table(id varchar(3) , level int)asbegin  declare @level int  set @level = 1  insert into @t_level select @id , @level  while @@ROWCOUNT > 0  begin    set @level = @level + 1    insert into @t_level select a.id , @level    from tb a , @t_Level b    where a.pid = b.id and b.level = @level - 1  end  returnendgo --調用函數查詢001(廣東省)及其所有子節點select a.* from tb a , f_cid('001') b where a.id = b.id order by a.id/*id   pid  name       ---- ---- ---------- 001  NULL 廣東省002  001  廣州市003  001  深圳市004  002  天河區005  003  羅湖區006  003  福田區007  003  寶安區008  007  西鄉鎮009  007  龍華鎮010  007  松崗鎮 (所影響的行數為 10 行)*/ --調用函數查詢002(廣州市)及其所有子節點select a.* from tb a , f_cid('002') b where a.id = b.id order by a.id/*id   pid  name       ---- ---- ---------- 002  001  廣州市004  002  天河區 (所影響的行數為 2 行)*/ --調用函數查詢003(深圳市)及其所有子節點select a.* from tb a , f_cid('003') b where a.id = b.id order by a.id/*id   pid  name       ---- ---- ---------- 003  001  深圳市005  003  羅湖區006  003  福田區007  003  寶安區008  007  西鄉鎮009  007  龍華鎮010  007  松崗鎮 (所影響的行數為 7 行)*/ drop table tbdrop function f_cid

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.