存储过程创建与调用(在SQL中)

存储过程

封装一段SQL语句,让SQL语句当成一个整体(编译过),将来调用整体,性能高一些。
大概类似于C#中方法。方法名,方法参数列表,返回值,输入参数in,输出参数out
存储过程也有参数,也有返回值,输入参数,输出参数

--1。判断某个存储过程是否已经存在,存在先删除,再创建


if exists (select * from sysobjects where id=object_id(N'p_studentinfo_insert'))
	drop procedure p_studentinfo_insert
go

--2。如何定义一个存储过程   procedure缩写成proc

create proc p_studentinfo_insert
	--参数列表,定义格式:参数名称 参数类型。每个参数以英文逗号分割,最后一参数不加逗号
	--输入参数(类似于C#中形式参数)
	@StudentName varchar(50),
	@Score int,
	--输出参数:必须赋值,注意输出参数不是存储过程的返回值
	@ReturnValue int output
as
begin
	-- begin和end之间是存储过程的业务逻辑,业务逻辑将来可以是复杂业务逻辑。
	insert into StudentInfo(StudentName, Score) values (@StudentName, @Score);
	set @ReturnValue = @@rowcount;  --SQL执行时影响的行数
	return 100;
end
go

在sql server中调用存储过程

execute缩写成exec

declare @rv int  --用来接收输出参数
declare @return int  --用来接收返回值
exec @return = p_studentinfo_insert '张三2',82,@rv output
print @rv;
print @return;

没有输出参数,没有返回值的存储过程

if exists (select * from sysobjects where id=object_id(N'p_studentinfo_update'))
	drop procedure p_studentinfo_update
go

--定义一个简单的存储过程,没有输出参数,没有返回值
create proc p_studentinfo_update
	@StudentName varchar(50),
	@Score int,
	@StudentId int
as
begin
	update StudentInfo set StudentName = @StudentName,Score = @Score
	where StudentId = @StudentId
end
go

--调用存储过程
--exec p_studentinfo_update '李四',100,101
--exec p_studentinfo_update '李四2',90,102

你可能感兴趣的:(C#与SQLServer,sql,数据库,sqlserver,笔记)