Redian新闻
>
谁能帮我看看这个sql query的优化
avatar
谁能帮我看看这个sql query的优化# Database - 数据库
s*n
1
想要查找一个目录的某个级的子目录, 返回在一个表中.
看看我写的, 挺傻的, 不知道怎么可以优化下
目录关系存在proj_tab里面
create function getSubFolder(@level int, @folderId int)
returns @retab table(folderId int)
as
begin
declare @temp table(folderId int)
insert into @temp select folderId from proj_tab where parentno = @
folderId
select @level = @level -1
while @level <> 0
begin
insert into @retab select folderId from proj_tab where parentno in (
select folderId from @temp)
delete from @temp
insert into @temp
avatar
m*0
2
1) use truncate instead of del
2) depends on depth and size of ur tree, if it can go up to 5 or event more, and you do reads more than writes, you might want to change the logic completely, add one more column called depth, and change column parent to column ancestor, and each node will have all the info about all of its ancestor, if a node in lvl 5 is to be inserted, then it should also insert 4 more rows for each of its ancestor.
in this way, u will have instant results back when u do select.

【在 s******n 的大作中提到】
: 想要查找一个目录的某个级的子目录, 返回在一个表中.
: 看看我写的, 挺傻的, 不知道怎么可以优化下
: 目录关系存在proj_tab里面
: create function getSubFolder(@level int, @folderId int)
: returns @retab table(folderId int)
: as
: begin
: declare @temp table(folderId int)
: insert into @temp select folderId from proj_tab where parentno = @
: folderId

avatar
B*g
3
顶一个。没有connected by,苦呀。

【在 s******n 的大作中提到】
: 想要查找一个目录的某个级的子目录, 返回在一个表中.
: 看看我写的, 挺傻的, 不知道怎么可以优化下
: 目录关系存在proj_tab里面
: create function getSubFolder(@level int, @folderId int)
: returns @retab table(folderId int)
: as
: begin
: declare @temp table(folderId int)
: insert into @temp select folderId from proj_tab where parentno = @
: folderId

avatar
j*n
4
if MS SQL Server 2005, go books online and look for "Recursive Queries Using
Common Table Expressions", there is an example exactly what you want.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。