sql server 存储过程

来源:互联网 发布:u盘制作linux安装盘 编辑:程序博客网 时间:2024/06/06 21:04
SQL中存储过程和函数的区别

本质上没区别。只是函数有如:只能返回一个变量的限制。
而存储过程可以返回多个。而函数是可以嵌入在sql中使用的,
可以在select中调用,而存储过程不行。执行的本质都一样。


select * from t_student;

-- 删除存储过程
DROP PROCEDURE outStudent;

-- 输入一个带参数的 存储过程
-- 调用存储过程


-- 输入两个参数 存储过程
create proc outStudent
(@studentId int)
as
select * from t_student where id=@studentId;

exec outStudent 1;


sp_help t_student;

-- 创建 传入参数的存储过程
DROP PROCEDURE outStudentTwo;

create proc outStudentTwo
(@studentId int, -- int 类型
@studentName varchar(30), -- string 类型 长度范围 是根据你参数值的 范围 匹配
@birthday date -- 时间类型
)
as
select * from t_student where id=@studentId and name=@studentName and birsday=@birthday

select * from t_student;

-- 执行存储过程 并且传入 参数 多参数用逗号分隔

exec outStudentTwo 1,'你好','1990-09-08';





DROP PROCEDURE outStudentThree;



set xact_abort on; -- 语句产生运行时错误,整个事务将终止并回滚。为 OFF 时,只回滚产生错误的
go
create proc outStudentThree
(@studentId int) -- 传入的参数
as
begin tran -- 开启事务
DECLARE @classname varchar(200) -- 申明变量
update t_student set name='你好1' where id=@studentId;
select @classname=class_name from t_student t1 -- 变量赋值
inner join t_class t2 on t1.class_id=t2.id
where t1.id=@studentId;
update t_class set class_name='苹果班1' where class_name=@classname -- 使用变量
commit tran -- 提交事务


-- 执行存储过程
exec outStudentThree 1

select * from t_student;
select * from t_class;

-- 存储过程中的事务管理


-- 函数的使用

drop function selectStudentId;

create function selectStudentId
(@student_name varchar(20))
returns int
as
begin
declare @studentId int
select @studentId=id from t_student where name=@student_name;
return @studentId
end

exec selectStudentId '你好1'
原创粉丝点击