游标的使用

      虽然大部分的时候我们并不要用到游标的操作,但是在某些的场合使用游标确实能给我们带来许多的方便,下面就是我使用游标的实例。
--获取该组织和该岗位下的用户名,字符串返回
  CREATE FUNCTION GetMyNames (@OrgID int,@PostID int)  
RETURNS nvarchar(
500)
AS  
BEGIN 
declare @MyNames nvarchar(
500)
declare @tempstr nvarchar(
20)

set @MyNames=''
set @tempstr=''
declare name_cursor cursor 
for  --申明游标
select archives.name 
from myorguser left join 
archives on myorguser.archivesid
=archives.archivesid 
where myorguser.orgid=@OrgID and myorguser.postid=@PostID
open name_cursor   
--打开游标
fetch next from name_cursor into @tempstr  
---获取数据的值到变量
while @@fetch_status=0  --如果不等于0就没有数据了
begin
    
set @MyNames=@MyNames+@tempstr+','
    
--print @names
    
--print @temp
    fetch next from name_cursor into @tempstr  
--获取数据
end
if len(@MyNames)>0
begin
set @MyNames=substring(@MyNames,1,len(@MyNames)-1)
end
close name_cursor  
--关闭游标
deallocate name_cursor  
--释放游标
    
return @MyNames
END


原文地址:https://www.cnblogs.com/ringwang/p/1111905.html