亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我的問題到底在哪,我這樣也不行,好像我注釋到的循環跟本沒作用?

我的問題到底在哪,我這樣也不行,好像我注釋到的循環跟本沒作用?

弒天下 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 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號