--資料指標Cursor
--宣告靜態資料指標
declare stuCursor cursor
static --靜態指標
for select 學號,姓名,電話 from 學生
open stuCursor
declare @id char(4), @name varchar(12), @tel varchar(15)
fetch first from stuCursor into @id,@name,@tel
while @@FETCH_STATUS=0
begin
print 'id='+@id+',name='+@name+',tel='+@tel
fetch next from stuCursor into @id,@name,@tel
end
close stuCursor
deallocate stuCursor
go
declare stuCursor cursor
keyset --key指標
for select 學號,姓名,電話 from 學生
open stuCursor
declare @id char(4), @name varchar(12), @tel varchar(15)
fetch first from stuCursor into @id,@name,@tel
while @@FETCH_STATUS<>-1
begin
if @@FETCH_STATUS=-2
print '當前資料遺失'
else
print 'id='+@id+',name='+@name+',tel='+@tel
fetch next from stuCursor into @id,@name,@tel
end
close stuCursor
deallocate stuCursor
--fetch first 指標移至第一筆資料
--fetch next 指標移至下一筆資料
--fetch prior 指標移至上一筆資料
--fetch last 指標移至最後一筆資料
--fetch absolute 3 --移動到第三筆資料
--fetch relative 3 --移動到目前指標位置的後面三筆資料
--fetch relative -3 --移動到目前指標位置的前面三筆資料
----------------------------
declare staff_cursor cursor
static
for select 身份證字號,姓名 from 員工
open staff_cursor
declare @id char(10), @name varchar(12)
if @@CURSOR_ROWS>0
begin
fetch first from staff_cursor into @id,@name
while @@FETCH_STATUS=0
begin
print @name
fetch relative 2 from staff_cursor into @id,@name
end
end
close staff_cursor
deallocate staff_cursor
go
------------------------------------------------------
declare staff_cursor cursor
static
for select 身份證字號,姓名 from 員工
open staff_cursor
declare @id char(10), @name varchar(12), @inc int
if @@CURSOR_ROWS>0
begin
set @inc=@@CURSOR_ROWS/3
fetch first from staff_cursor into @id,@name
while @@FETCH_STATUS=0
begin
print @name
fetch relative @inc from staff_cursor into @id,@name
end
end
close staff_cursor
deallocate staff_cursor
go
--更新與刪除
--牽涉到並行控制問題
-------------------------------
declare staff_cursor cursor
keyset
for select 身份證字號,姓名,薪水 from 員工
open staff_cursor
declare @id char(10), @name varchar(12), @salary money
if @@CURSOR_ROWS>0
begin
fetch first from staff_cursor into @id,@name,@salary
while @@FETCH_STATUS=0
begin
print '目前的薪水'+cast(@salary as varchar)
set @salary*=1.03
update 員工 set 薪水=@salary where current of staff_cursor
fetch next from staff_cursor into @id,@name,@salary
end
end
close staff_cursor
deallocate staff_cursor