實現子孫樹查詢的經典SQL語句

下面介紹的SQL語句非常經典,該SQL語句實現子孫樹查詢,該SQL語句可以直接在查詢分析器中執行,供您參考。

  1. --生成表  
  2. create table MENU(id int,mname char(50),parent int)  
  3.  
  4. --插入數據  
  5. insert into MENU   
  6. select 1,'新聞',Null union all  
  7. select 2,'房產',Null union all  
  8. select 3,'科技新聞',1 union all  
  9. select 4,'社會新聞',1 union all  
  10. select 5, 'IT新聞',3 union all  
  11. select 6, '航天新聞',3   
  12.  
  13. --實現查詢新聞子孫樹  
  14. Declare @s varchar(1000)   
  15. select @s=','+cast(id as varchar(20))+'' from MENU where id=1 
  16.  
  17. while  @@rowCount>0   
  18.  
  19. --charindex:返回字符串中指定表達式的起始位置  
  20.   select   @s=@s+','+cast(id as varchar) from MENU       
  21.             where charindex(','+cast(id as varchar)+',',@s+',')=0    
  22.    
  23.             and   charindex(','+cast(parent as varchar)+',',@s+',')>0   
  24.  
  25.  
  26. select * from MENU where charindex(','+cast(id as varchar)+',',@s+',')>0  
  27.  
  28. --刪除表  
  29.  
  30. drop table MENU  
發佈了18 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章