这个怎么用实现?

hanjs 2008-06-05 03:02:00
if object_id('tree') is not null drop table tree

create table tree(id varchar(10),code varchar(10),name varchar(20),pid varchar(10))
insert into tree values ('1','01','A学校',null)
insert into tree values ('2','0101','计算机学院','1')
insert into tree values ('3','0102','外语学院','1')
insert into tree values ('4','02','B学校',null)
insert into tree values ('5','0201','建筑学院','4')
insert into tree values ('6','020101','城市规划','5')
insert into tree values ('7','0202','土木工程学院','4')
go

我想写一个函数,只有参数 pid
如果传入 null,则返回所以 id
否则返回此pid的所有下级 id

如传入 4

则返回
5
6
7

返回table类型的,如果能用递归最好了
...全文
70 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
hanjs 2008-06-05
  • 打赏
  • 举报
回复
我也服了,csdn的怎么总看不全帖子呢??

每次我都只能看到2楼。

怎么想的??

人家itpub就没有这个限制!
hery2002 2008-06-05
  • 打赏
  • 举报
回复
.......
hanjs 2008-06-05
  • 打赏
  • 举报
回复
函数内不允许
print
exec

太垃圾了吧
Herb2 2008-06-05
  • 打赏
  • 举报
回复
那就用存储过程吧
hanjs 2008-06-05
  • 打赏
  • 举报
回复
可是当我表名是动态传入的话,就只能用动态sql了。
Herb2 2008-06-05
  • 打赏
  • 举报
回复
疯子的可以呀。
hanjs 2008-06-05
  • 打赏
  • 举报
回复
我自己写出看来了

create function uf_getTree(@pid varchar(30))
returns @tree table(id varchar(30))
as
begin
if @pid is null
insert into @tree select id from tree
else
declare @sql varchar(500)
declare @id varchar(30)
declare cur cursor for select id from tree where pid=@pid
begin
--set @sql='declare cur cursor for select id from tree where pid='+@pid
--exec(@sql)
open cur
fetch cur into @id
while (@@fetch_status=0)
begin
insert into @tree values (@id)
insert into @tree select * from dbo.uf_getTree(@id)
fetch cur into @id
end
close cur
deallocate cur
end
return
end
go

可是注释的部分为何不能用动态的处理

报下面的错误

服务器: 消息 443,级别 16,状态 2,过程 uf_getTree,行 13
在函数内不正确地使用了 'EXECUTE'。

wzy_love_sly 2008-06-05
  • 打赏
  • 举报
回复
--测试数据
CREATE TABLE tb(ID char(3),PID char(3),Name nvarchar(10))
INSERT tb SELECT '001',NULL ,'山东省'
UNION ALL SELECT '002','001','烟台市'
UNION ALL SELECT '004','002','招远市'
UNION ALL SELECT '003','001','青岛市'
UNION ALL SELECT '005',NULL ,'四会市'
UNION ALL SELECT '006','005','清远市'
UNION ALL SELECT '007','006','小分市'
GO

--查询指定节点及其所有子节点的函数
CREATE FUNCTION f_Cid(@ID char(3))
RETURNS @t_Level TABLE(ID char(3),Level int)
AS
BEGIN
DECLARE @Level int
SET @Level=1
INSERT @t_Level SELECT @ID,@Level
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
INSERT @t_Level SELECT a.ID,@Level
FROM tb a,@t_Level b
WHERE a.PID=b.ID
AND b.Level=@Level-1
END
RETURN
END
GO

--调用函数查询002及其所有子节点
SELECT a.*
FROM tb a,f_Cid('002') b
WHERE a.ID=b.ID
/*--结果
ID PID Name
------ ------- ----------
002 001 烟台市
004 002 招远市
--*/


看例子写吧,老写很麻烦哦...

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧