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

--关键字用[]
select * from [User]

use SHMSDB
declare @i int
declare @name varchar
declare usercursor cursor
for select [username] from [user]
open usercursor
select @i=count(*) from [user]
select @name=UserName from [user]
--读取下一行数据把读取的数据放在变量中
fetch next from usercursor
--是系统关键字代表游标取值的状态等于0表示取到了一行数据 否则表示最后一行数据读完了!
while @@fetch_status=0 and @i>1
begin
fetch next from usercursor into @name
set @i=@i-1
end
close usercursor
--删除游标引用
deallocate usercursor

为什么只能查询到第一条数据,
而for select [username] from [user],
while @@fetch_status=0 and @i>1
begin
fetch next from usercursor set @i=@i-1
end
这样能循环出每一条数据,?
补充问题:
Fetch usercursor into @name
怎么你的这里不要 Fetch next from。。。,我以前没用过游标,谢谢你详解。
还有:
use SHMSDB

declare @i int
declare @index int
declare @name varchar(100)
declare @strName varchar(8000)
select @index=0
declare usercursor cursor

for select [username] from [user]
open usercursor
select @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+','+'字符串'
--end
close usercursor
--删除游标引用
deallocate usercursor

弑天下
浏览 128回答 2
2回答

qq_花开花谢_0

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

慕的地10843

你这个 游标 有问题。修改如下:select * from [User]use SHMSDBdeclare @i intdeclare @name varchar(100)declare @name_str varchar(8000)select @i = 0, @name = '', @name_str = ''declare usercursor cursorfor select [username] from [user]open usercursorwhile @@fetch_status = 0 and @i < 100 -- 最大循环100次begin--读取下一行数据把读取的数据放在变量中Fetch usercursor into @nameif @name_str <> ''set @name_str = @name_str +','set @name_str = @name_str + @nameset @i = @i + 1endclose usercursordeallocate usercursorprint '你游标循环了'+cast(@i as varchar)+'次,用户名字符串为:'+@name_str
打开App,查看更多内容
随时随地看视频慕课网APP