sqlserver数据库触发器和存储过程案例学习

时间:2022-01-30 08:14:19
 
--创建表
create table zhuangzhan
(
name nvarchar(10),
code varchar(20)
);
--往表添加一列
alter table zhuangzhan add descition int;
--添加数据
select * from zhuangzhan
insert zhuangzhan values('王五','',10000);
insert zhuangzhan values('李四','',0); --给表创建触发器用于添加数据出发,不允许添加code相同的数据
alter trigger mytrigger on zhuangzhan
for insert
as
begin tran
if exists(select code from zhuangzhan group by code having count(code)=2)
begin
rollback tran
end
else
begin
commit tran
end
end
--测试
insert zhuangzhan values('王五','',1);
--移除存储过程
drop procedure oneTOother_proc
--创建存储过程
create proc myproc
(
--输入参数
@names nvarchar(20),
@code varchar(20),
@i int output --输出参数
)
as
declare @counts int
begin tran
select @counts=count(code) from zhuangzhan where code=@code
if @counts>=1
begin
set @i=1
rollback tran
end
else
begin
insert into zhuangzhan values(@names,@code,1)
commit tran
set @i=0
end
go
select * from zhuangzhan
declare @i int
exec myproc'EXO','',@i output print @i
--模拟银行转账,实现事物的用法
create proc oneTOother_proc
(
--输入参数
@outMoney int,--转帐金额
@formPeople varchar(20),--汇款人
@toPeopleCode varchar(20)--收款人账号
)
as
declare @yuE int --汇款人余额
declare @i int
declare @tocode int
declare @error int --定义错误号记录
select @yuE=descition from zhuangzhan where name=@formPeople
select @i=COUNT(name) from zhuangzhan where name=@formPeople
if(@yuE<@outMoney)
begin
print @formPeople+'账户余额不足'
return
end
else if(@i=0)
begin
print '汇款人'+@formPeople+'不存在'
return
end
else select @tocode=count(code) from zhuangzhan where code=@toPeopleCode
if(@tocode<1)
begin
print '收款人账号'+@toPeopleCode+'不存在'
return
end
else
begin tran --开始事物
begin
update zhuangzhan set descition=descition-@outMoney where name=@formPeople
set @error=@error+ @@ERROR
update zhuangzhan set descition=descition+@outMoney where code=@toPeopleCode
set @error=@error+ @@ERROR
end
if(@error>0)
begin
rollback transaction
end
else
begin
commit tran
print @error
print @formPeople+'给账号为:'+@toPeopleCode+'汇款'+cast(@outMoney as varchar(10))+'元'
end
go select * from zhuangzhan exec oneTOother_proc 500000,'王五',''