SqlServer存储过程,学习

时间:2023-03-09 19:39:48
SqlServer存储过程,学习
存储过程:存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。功能强大,限制少

如何调用存储过程
 --无参数的存储过程
exec sp_databases; --有参数的
exec sp_helpdb TestDataBase; exec sp_renamedb TestDataBase, TDB;
-- 当参数较多的时候,建议使用显示赋值
exec sp_renamedb @newname='Testdatabase', @dbname='TDB';

创建,修改无参存储过程:

创建:

-- 一个无参的查询存储过程
/*
create proc usp_存储过程名
as
查询步骤
*/
go
create proc usp_spFenYe
as
select * from dbo.fn_fenye(1,10);--一个分页的fn,获取第一页的数据,10条/页
go

修改已有的存储过程usp_Test,以实现转账为例子(开启事务),

 alter proc usp_Test
as
begin
begin transaction
declare @myError int;
set @myError = 0;
update bank set balance=balance + 900 where cid='';
set @myError += @@ERROR;
update bank set balance=balance - 900 where cid='';
set @myError += @@ERROR;
if(@myError > 0)
begin
rollback transaction;
end
else
begin
commit transaction;
end
end;
go select * from bank; exec usp_Test;

建个有参数的存储过程,继续转账:

 create proc usp_ZZ2
@from char(4), --从那里转
@to char(4), --转到哪里
@money money --金额
as
begin
begin transaction
declare @myError int;
set @myError = 0;
update bank set balance=balance - @money where cid=@from;
set @myError += @@ERROR;
update bank set balance=balance + @money where cid=@to;
set @myError += @@ERROR;
-- 什么时候提交,什么时候回滚?
if(@myError > 0)
begin
rollback transaction;
end
else
begin
commit transaction;
end
end
go select * from bank; exec usp_ZZ2 '', '', 90; exec usp_ZZ2 @money=500, @from = '', @to = ''; exec usp_ZZ2 '', '', 410; go

依然在转账

 create proc usp_ZZ3
@from char(4),
@to char(4),
@money money
as
begin
begin transaction
declare @last money;
set @last = (select balance from bank where cId=@from);
if(@last - 10 >= @money)
-- bank表里有一个检查约束,余额要大于等于10
begin
update bank set balance=balance - @money where cid=@from;
update bank set balance=balance + @money where cid=@to;
commit;
select '转账成功';
end
else
begin
rollback;
select '转账失败';
end
end
go exec usp_ZZ3 '', '', 900; select * from bank;
 给存储过程的参数设置默认值,示例:
 create proc usp_testDefault
@str nvarchar(50) = '默认值'
as
select @str; exec usp_testDefault '我是传进来的参数啊';

output参数怎么用,还在转(转账),修改存储过程zz4;

 -- 带有output参数的存储过程

 go

 create proc usp_ZZ4
@from char(4),
@to char(4),
@money money,
@state int output
-- 这个state表示需要在存储过程中赋值,外面使用的参数
as
begin
begin transaction
declare @last money;
set @last = (select balance from bank where cId=@from);
if(@last - 10 >= @money) begin
update bank set balance=balance - @money where cid=@from;
update bank set balance=balance + @money where cid=@to;
commit;
set @state = 1;--1表示转账成功
end
else
begin
rollback;
set @state = 0;--转账失败
end
end
go
----------------
-- 使用
declare @State int;
exec usp_ZZ4 '', '', 1000, @State output;
exec usp_ZZ4 @from = '', @to = '', @money = -501, @state = @State output; select @State;