問題: 書屬于某個分類
分類的記錄屬于其他分類
分類表的內容如下:
pkid |
description |
parentid |
1 |
外語 |
0 |
2 |
計算機 |
0 |
3 |
文學 |
0 |
4 |
程序設計 |
2 |
5 |
C# |
4 |
書表內容如下:
pkid |
categoryid |
bookname |
1 |
2 |
計算機文化 |
2 |
4 |
Java編程思想 |
3 |
5 |
C# 高級編程 |
4 |
1 |
7777 |
5 |
3 |
4444 |
現在根據分類2,應該查詢出
計算機文化,Java編程思想,C# 高級編程三本書.
Sp如下:
create proc Pro_QueryBookByCateId
@cateid varchar(10) = '2'
as
begin
create table #T
(
[ID] int,
ParentID int,
[Level] INT
)
declare @s nvarchar(4000)
set @s = N'declare @i int set @i = 1
insert into #T select pkid,parentid,@i from tcategory where pkID='+ @cateid +N'
while @@rowcount<>0
begin
set @i = @i + 1
insert into #t
select
a.pkid,a.parentid,@i
from tcategory a,#t b
where a.parentid=b.id and b.Level = @i-1
end'
exec(@s)
select tbook.pkid,tbook.descriptions
from #T a,tbook
where a.[id]=tBook.categoryid
end