1、事务
事务由若干条T-SQL指令组成的逻辑工作单元执行的一系列操作,这些操作为一个整体,要么全部执行,要么全部撤销
创建事务的语法:
create table bank
(
customerld int primary key identity(1,1),
customerldName char(10),
customerldMoney money check(customerldMoney>=1)
)
insert into bank values('张三',1000)
insert into bank values('李四',1)
begin transaction(开始) 也可以 缩写成 begin tran
commit transaction | commit tran 提交(执行)
rollback transactio | rollback tran 回滚(撤销)
begin transaction--开始
declare @a int
set @a = 0
update bank set customerldMoney=customerldMoney-500 where customerldName='张三'
set @a=@a+@@ERROR
update bank set customerldMoney=customerldMoney+500 where customerldName='李四'
set @a=@a+@@ERROR
if @a=0--判断
begin
commit transaction--提交
print '转账成功!'
end
else
begin
rollback transaction--回滚
print '转账失败!'
end
select * from bank
2、游标
游标实际上是一种能从包括多条数据记录的结果集中提取记录的机制
游标允许定位到结果集的特定行
从结果集中检索一行或者多行数据
支持多结果集当前位置的行进行修改
声明游标的语法流程:
声明游标
declare a cursor scroll for select customerldName,customerldMoney from bank
打开游标
open a
定义变量
declare @name varchar(10), @b int
使用游标
fetch first from a into @name,@b
while @@FETCH_STATUS=0
begin
print '姓名:'+@name+'|'+space(6)+'余额:'+convert(varchar(10),@b)
fetch next from a into @name,@b
end
--关闭游标
close a
--释放游标
deallocate a