ITPub博客

首页 > 数据库 > 数据库开发技术 > 递归存储过程中使用cursor

递归存储过程中使用cursor

原创 数据库开发技术 作者:kitesky 时间:2006-12-15 17:59:42 0 删除 编辑

递归存储过程中使用cursor可以用来向上遍历有向图,找出其直系父辈。

注意定义成local类型的cursor !

[@more@]

PROCEDURE sp_get_all_lineal_parent
@node_id int,
@lineal_path varchar(200) output
with encryption
AS

SET NOCOUNT ON
BEGIN
IF ISNULL(@lineal_path, 'NULL') = 'NULL' SET @lineal_path = ''
IF EXISTS( select DependentProductID from Dependence_TB where ProductID = @node_id )
BEGIN
DECLARE cur_parent_node CURSOR FAST_FORWARD local FOR
SELECT DependentProductID
FROM Dependence_TB
WHERE ProductID = @node_id

DECLARE @parent_node_id int

OPEN cur_parent_node
FETCH NEXT FROM cur_parent_node INTO @parent_node_id
WHILE @@FETCH_STATUS = 0
BEGIN
set @lineal_path = @lineal_path + ',' + cast(@parent_node_id as varchar)
exec sp_get_all_lineal_parent @parent_node_id, @lineal_path output

FETCH NEXT FROM cur_parent_node INTO @parent_node_id
END
CLOSE cur_parent_node
DEALLOCATE cur_parent_node
END
insert into ##temp_a(a) select 100
select * from ##temp_a
END

--调用示例begin
declare @path varchar(200)
create table ##temp_a(a int)
EXEC sp_get_all_lineal_parent 12, @path output
drop table ##temp_a
select @path
end

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/66009/viewspace-884175/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: DBCC的归纳
请登录后发表评论 登录
全部评论

注册时间:2009-04-22

  • 博文量
    273
  • 访问量
    2225401