ITPub博客

首页 > 数据库 > SQL Server > SQL Server 中创建返回值为表的函数其中包括游标的使用方法

SQL Server 中创建返回值为表的函数其中包括游标的使用方法

原创 SQL Server 作者:liahtobjtosh 时间:2009-09-30 19:50:28 0 删除 编辑
SQL Server 中创建返回值为表的函数其中包括游标的使用方法[@more@]

CREATE FUNCTION GetOneLayGroupChild_li(@paraParentId as smalldatetime) --输入参数
returns @tChildGroup table(cGroupId int, pGroupId int) --返回参数
AS
begin

declare @tParentId int,@tChildId int
--第一步.声明一个名为Order_Cursor的游标.游标为一个行集。所以下面为一个select语句
declare Order_Cursor cursor
for select pkid,parentid from [group]
--第二步.打开游标,检索数据并填充游标
open Order_Cursor
--第三步.fetch会使游标移到下一条记录,并将游标返回的每个列的数据分别赋值给本地变量。
--通常会使用while来反复从游标中获取记录行,直到游标不再返回任何行为止。用@@fetch_status
--来确定是否还能够从游标中获取行
fetch next from Order_Cursor into @tChildId,@tParentId
while @@fetch_status=0
begin
if (@tParentId = @paraParentId)
begin
insert into @tChildGroup(cGroupId,pGroupId)
values(@tChildId,@tParentId)
end --if
fetch next from Order_Cursor into @tChildId,@tParentId
end --while
--关闭游标,释放数据。但可以使用open命令再次打开它
close Order_Cursor
--释放游标,释放相关的内存,并删除游标的定义
deallocate Order_Cursor

return
end
******

注:在函数中不允许有修改数据库中表的语句,如Insert,update

******

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

请登录后发表评论 登录
全部评论

注册时间:2009-09-19

  • 博文量
    48
  • 访问量
    249171