sqlserver 游標寫法


1.簡單游標

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
declare  m_cursor  cursor  scroll  for
select   Address,PeopleId  from   PeopleDetail
 
open  m_cursor
declare    @Address  varchar (50), @PeopleId  int
 
fetch  next  from  m_cursor  into  @Address,@PeopleId
while @@FETCH_STATUS=0
begin
     print @Address +  convert ( varchar (3), @PeopleId)
     fetch  next  from  m_cursor  into  @Address,@PeopleId
end
 
close  m_cursor
deallocate  m_cursor

2.用於更新的游標 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- 定義游標
declare  m_cursor  cursor  scroll  for
select  a.Id,b.Address  from   People a  left  join  PeopleDetail b  on  a.Id=b.PeopleId
for  update
-- 打開游標
open  m_cursor
declare    @Address  varchar (50), @Id  int
--填充數據
fetch  next  from  m_cursor  into  @Id,@Address
--假如檢索到了數據,才處理
while @@FETCH_STATUS=0
begin
     update  People  set   Address=@Address  where  current  of  m_cursor
     --填充下一條數據
     fetch  next  from  m_cursor  into  @Id,@Address
end
-- 關閉游標
close  m_cursor
--釋放游標
deallocate  m_cursor

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM