SQL递归函数

房东的猫 提交于 2020-01-17 04:06:31

生成一张表,添加数据

DROP table IF EXISTS Dept;
create table Dept(ID int,ParentID int,msg varchar(20))   
insert into Dept select 1,0,'中国'  
insert into Dept select 2,1,'上海'   
insert into Dept select 3,1,'浙江'  
insert into Dept select 4,2,'普陀区'   
insert into Dept select 5,3,'杭州'   
insert into Dept select 6,5,'西湖区'   
insert into Dept select 7,6,'双浦镇'   
go

在这里插入图片描述
递归函数:

Create function GetChild(@ID varchar(10))   
returns @t table(ID varchar(10),ParentID varchar(10),Level int,msg varchar(20))   
as  
begin  
    declare @i int  
    set @i = 1   
--insert into @t select @ID,@ID,0 --当前级,本级,如果不要的话可以注释掉或再加个参数来选择操作   
    insert into @t select ID,ParentID,@i ,msg from Dept where ParentID = @ID   
  
    while @@rowcount<>0   
    begin  
        set @i = @i + 1   
        insert into @t   
        select  
            a.ID,a.ParentID,@i,a.msg   
        from  
            Dept a,@t b   
        where  
            a.ParentID=b.ID and b.Level = @i-1   
    end  
    return  
end 

调用函数

select * from dbo.GetChild(3);

在这里插入图片描述
创建多声明表值函数的语法:

1 create function [函数的所有者].函数名(标量参数 [as] 标量参数类型 [=默认值])
2 returns @表变量 table 表的定义(即列的定义和约束)
3 [with {Encryption | Schemabinding }]
4 [as]
5 begin
6     函数体(即 Transact-SQL 语句)
7     return
8 end

sql server中的while循环语句:

while 条件

begin 

  .......

end

@@rowcount来作递归或循环
比如下面示例:

declare @n int
set @n=1
select * from client_goods where id=@n

while @@rowcount>0
begin
    set @n=@n+1
    select * from client_goods where id=@n
end

这个示例是先查询client_goods中是否有id=1的数据,如果有,再查询是否有id=2的数据,一直查下去,直到id没有连续为止。当然大家在看这个示例的时候不要考虑这个示例的意义,它只是说明了@@rowcount可以作为循环条件来用。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!