游标:即从某一结果集中逐一地读取一条记录。缺点:所占资源大。
游标四部分:1.DECLARE游标 2.open游标 3.从一个游标中FETCH信息4.CLOSE或DEALLOCATE游标
声明游标:
declare cur_authors cursor
for
select id,name,phone,address from authors
for update(for read only)(for update of au_lname,au_fname /*只允许修改这两列*/)
FETCH命令语法规则为:
FETCH
[[NEXT|PRIOR|FIRST|LAST|ABSOLUTE{n|@nvar}|RELATIVE{n|@nvar}]FROM]cursor_name
[INTO @variable_name1,@variable_name2...]
进行定位修改或删除游标中数据的语法规则为:
UPDATE table_name
set column_name=expression
where current of cursor_name
DELETE from table_name
where current of cursor_name
游标例子1:
declare @au_id varchar(11),@au_lname varchar(40),@au_fname varchar(20)
declare authors_cur cursor
for
select au_id,au_lname,au_fname from authors
for update of au_id,au_lname,au_fname
open authors_cur
fetch next from authors_cur into @au_id,@au_lname,@au_fname
while @@fetch_status=0
Begin
if @au_id='1772-32-1176'
update authors
set au_lname='smith',au_fname='jake'
where current of authors_cur
fetch next from authors_cur into @au_id,@au_lname,@au_fname
end
deallocate authors_cur/*释放游标*/(close the cursor)
游标例子2:
declare @Id int,@DepartmentId int
-- 1.declare cursor
DECLARE risk_cur CURSOR FOR
select Id,DepartmentId from ProtectionRisk
-- 2.open cursor
OPEN risk_cur
-- 3.fetch data from cursor then use it
FETCH risk_cur INTO @Id,@DepartmentId --select fields in the step 1
WHILE @@FETCH_STATUS=0
BEGIN
update Entity_To_ProtectionRisk set DepartmentId=(select DepartmentId from ProtectionRisk where id=@Id) where ProtectionRiskId=@Id
FETCH NEXT FROM risk_cur INTO @ID,@DepartmentId
END;
-- 4.close cursor
CLOSE risk_cur;
-- 5.release cursor
DEALLOCATE risk_cur;