![](https://csdnimg.cn/release/download_crawler_static/87531718/bg5.jpg)
while (@@fetch_status=0)
begin
fetch next from c into @emp_id
update salary set work_age=(select'工龄'=round(datediff(mm,
sdate,(getdate()))/12,2) from salary where emp_id=@emp_id)where
emp_id=@emp_id
end
close c
deallocate c
10.创建游标
declare cursor_name(游标名) [scroll] (滚动游标) cursor for
select_statement
for read only(只读)/update of column_name_list(可更新的字段列表)
open cursor_name -- 打开游标
fetch next(取下一行数据)/prior(取前一行数据)/first(取第一行数据)/last(取
最后一条数据)/absolute(按绝对位置取数据)/relative(按相对位置取数据)
from cursor_name into fetch_target_list(变量列表)
close cursor_name --关闭游标
deallocate cursor cursor_name --释放游标
两个全局变量@@fetch_status,@@rowcount
@@fetch_status=0 表示成功完成 fetch 语句
@@fetch_status=-1 表示 fetch 语句执行有错误,或者当前游标位置已在结果集中
的最后一行,结果集中不再有数据
@@fetch_status=-2 表示提取的行不存在
@@rowcount 保存着游标结果集中提取的行数,如果结果集中所有行都被提取,则
@@rowcount 的值就是该结果集的总行数,关闭游标时,该@@rowcount 变量被删除.
11.使用事务(事务的优点,可以对数据进行回滚;缺点,建立临时回滚点,耗时
长,效率低下,大数据量操作不适宜)
begin tran/transaction
sql_statement(语句序列)
save tran save_point (设置保存点)
sql_statement(语句序列)
if @@error<>0 --@@error 为 0 表示未出错.@@error<>0 表示出错.
rollback tran save_point (回滚到事务保存点)
commit tran (提交事务)