为了账号安全,请及时绑定邮箱和手机立即绑定

我的问题到底在哪,我这样也不行,好像我注释到的循环跟本没作用?

我的问题到底在哪,我这样也不行,好像我注释到的循环跟本没作用?

弑天下 2022-09-17 15:11:26
--关键字用[]select * from [User]use SHMSDBdeclare @i intdeclare @name varchardeclare usercursor cursorfor select [username] from [user]open usercursorselect @i=count(*) from [user]select @name=UserName from [user]--读取下一行数据把读取的数据放在变量中fetch next from usercursor--是系统关键字代表游标取值的状态等于0表示取到了一行数据 否则表示最后一行数据读完了!while @@fetch_status=0 and @i>1beginfetch next from usercursor into @nameset @i=@i-1endclose usercursor--删除游标引用deallocate usercursor为什么只能查询到第一条数据,而for select [username] from [user],while @@fetch_status=0 and @i>1beginfetch next from usercursor set @i=@i-1end这样能循环出每一条数据,?补充问题:Fetch usercursor into @name怎么你的这里不要 Fetch next from。。。,我以前没用过游标,谢谢你详解。还有:use SHMSDBdeclare @i intdeclare @index intdeclare @name varchar(100)declare @strName varchar(8000)select @index=0declare usercursor cursorfor select [username] from [user]open usercursorselect @i=count(*) from [user]--读取下一行数据把读取的数据放在变量中fetch next from usercursor--是系统关键字代表游标取值的状态等于0表示取到了一行数据 否则表示最后一行数据读完了!--while @@fetch_status=0 and @index<@i--begin-- fetch next from usercursor into @name--set @strName=@strName+','--set @strName=@strName+@name-- set @i=@i-1--print cast(@i as varchar)+','+@strName+','+'字符串'--endclose usercursor--删除游标引用deallocate usercursor
查看完整描述

2 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

你的游标每一条数据都查询到了。
读取到第一条数据你把name赋值给@name,
读取到第二条数据,把name赋值给@name,所以@name永远只有一个值。
而且你这句select @name=UserName from [user]
也是如此,其实都查询到了,但是@name,只会保留最后一行数据的username

查看完整回答
反对 回复 2022-09-21
?
慕的地10843

TA贡献1785条经验 获得超8个赞

你这个 游标 有问题。修改如下:
select * from [User]

use SHMSDB
declare @i int
declare @name varchar(100)
declare @name_str varchar(8000)

select @i = 0, @name = '', @name_str = ''
declare usercursor cursor
for select [username] from [user]
open usercursor
while @@fetch_status = 0 and @i < 100 -- 最大循环100次
begin
--读取下一行数据把读取的数据放在变量中
Fetch usercursor into @name
if @name_str <> ''
set @name_str = @name_str +','
set @name_str = @name_str + @name
set @i = @i + 1
end
close usercursor
deallocate usercursor

print '你游标循环了'+cast(@i as varchar)+'次,用户名字符串为:'+@name_str


查看完整回答
反对 回复 2022-09-21
  • 2 回答
  • 0 关注
  • 127 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号