sql游标的使用

来源:互联网 发布:淘宝优惠券真的假的 编辑:程序博客网 时间:2024/04/29 04:54

 最近做一个项目涉及到商品分类信息的管理,采用树的形式来实现,即在数据库中每个条目信息包括一个ID和ParentID,在删除树的一个子树的时候遇到一个问题就是,在删除一个节点时要保存他的所有子节点,以便进一步删除,但是SQL没有数组的概念,只有用游标来实现,并通过存储过程的递归实现删除子树

 

go

create procedure TreeDeleteByID(@id int)
as declare @num int;
   
declare @temp int;
begin
    
select @num = count(*from [分类信息表] where [ParentID] = @id;
    
if @num > 0
        
begin 
---必须将游标定义为local,否则递归时会出现游标已定义的问题
            declare categoryCursor cursor local for select [ID] from [分类信息表] where [ParentID]= @id;
--打开游标
            open categoryCursor;
--将缓存中的值取出到@temp    
        fetch categoryCursor into @temp;
            
while (@@fetch_status = 0)
                
begin
                    
exec TreeDeleteByID @temp;
--取下一条记录        
                                          fetch next from categoryCursor  into @temp;
                
end
        
deallocate categoryCursor;
        
end
     
delete from [分类信息表]where [ID] = @id;    
end

go
原创粉丝点击