软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > SQL SERVER > SQL SERVER 函数递归取树状结构

SQL SERVER 函数递归取树状结构

表结构:
USE [Test]
GO
/****** 对象: Table [dbo].[PersonTree] 脚本日期: 09/25/2009 00:17:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PersonTree](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[ParentID] [int] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

SQL函数:

CREATE FUNCTION dbo.getPerson(@personID INT)
RETURNS @table TABLE(id INT, pname VARCHAR(50))
AS
BEGIN
--INSERT INTO @table SELECT id, pname FROM PersonTree WHERE parentid = @personID
DECLARE @id INT
DECLARE @pname VARCHAR(50)
DECLARE myCursor CURSOR FOR
SELECT id, pname FROM PersonTree WHERE parentid = @personID
OPEN myCursor
FETCH NEXT FROM myCursor INTO @id, @pname;
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @table VALUES(@id,@pname);
INSERT INTO @table SELECT * FROM dbo.getPerson(@id);
FETCH NEXT FROM myCursor INTO @id, @pname;
END

CLOSE myCursor
DEALLOCATE myCursor

RETURN
END
    相关阅读
    网友评论
    栏目导航
    推荐软件