2018.09.13
星期四
雨
1.事务
定义:
事务是由若干条T-SQL指令组成的作为单个逻辑工作单元执行的一系列操作,
这些操作作为一个整体一起向系统提交,要么全 部执行完成,要么全部撤销。
是一个不可分割的工作逻辑单元。
特性:
事务必须具备原子性,一致性,隔离性,永久性。
模式:
显示事务,隐式事务,自动提交事务。
事例:
begin tran abc
declare @x int
set @x=0
update bank set currentmoney=currentmoney-100 where customername='张三'
set @x=@x+@@ERROR
update bank set currentmoney=currentmoney+100 where customername='李四'
set @x=@x+@@ERROR
if(@x=0)
begin
commit tran
print '转账成功!'
end
else
begin
rollback tran
print '转账失败!'
end
select * from bank
2.游标
定义:
游标是一种能从包括多条数据记录的结果集中每次提取一条记录的机制。
功能:
允许定位到结果集中的特定行;
从结果集的当前位置检索一行或多行数据;
支持对结果集中当前位置的行 进行修改。
操作步骤:
--声明游标
declare yb cursor scroll
for select customername,currentmoney from bank
--打开游标
open yb
--使用游标
--声明变量
declare @name varchar(10),@money money
--读取游标的第一行
fetch first from yb into @name,@money
--循环
while @@FETCH_STATUS=0
begin
print @name+'的余额为'+convert(varchar(10),@money)+'元'
--读取游标的下一行
fetch next from yb into @name,@money
end
--关闭游标
close yb
--释放游标
deallocate yb