浅谈存储过程

一、直接附上代码,简单易懂

---------------------------------------------前提代码-----------------------------------------------------------------

create table student(
	id  int   not null  primary key  identity(1,1),	--主键自增,
	student_no   varchar(20)  not null,	--学号
	student_name  varchar(20)  not null,	--姓名
	subject_no   int   not null,	--课程表对应的号
	subject_name varchar(20)  not null,	--课程名
	score   int  not null	--成绩
);

insert  into student(student_no , student_name , subject_no , subject_name , score )
 values( 201601 , '张三' , 0001 , '数学' , 98),
( 201601 , '张三' , 0002 , '语文' , 66),
( 201602 , '李四', 0001 , '数学' , 60),
( 201602 , '李四' , 0003 , '英语' , 78),
( 201603 , '王五' , 0001 , '数学' , 99),
( 201603 , '王五' , 0002 , '语文' , 99),
( 201603 , '王五' , 0003 , '英语' , 98)
;

01、在SQLService里存储过程分为有参和无参

----------------------------------------无参数(不传进参数)----------------------------------------------------

--存储过程(无参)
create proc test  as
	select student_no,student_name,subject_name,score 
    from student 
    where subject_name='语文' and score<80;


--查询名为test的存储过程
exec test;

----------------------------------------有参数(传进参数)----------------------------------------------------

--存储过程(有参)
create proc test2 (
    @name nvarchar(8)    --自定义变量name;
)
 as
	select student_no,student_name,subject_name,score 
    from student 
    where subject_name=@name and score<80;

exec test2 '语文'; --这里传进一个参数'语文'。

二、简单来讲,存储过程类似于java里的自定义方法,传进一个参数,使用这个参数运行方法里的代码。

三、附上两个小练习,加深印象。

小练习01

--2.写一个存储过程,当输入subject_name的时候,可以查询出这个课程的成绩(score)、该课程的总成绩、学习这门课的总人数
create proc test001
(
	@a nvarchar(100)    --自定义变量
)as
select score ,(select sum(score) 
from student
where subject_name=@a) as 总成绩
     ,(select count(*) from student where subject_name=@a) as 人数
from student 
where subject_name=@a;

--调用这个存储过程
 exec test001 '语文';

小练习02

--2.写一个存储过程,当输入student_name的时候,可以查询出这个学生各科的成绩(score)、该学生的总成绩、该学生学习了多少门课
create proc proc_01
(
	@student_name nvarchar(50)
)
as
	select score 
	,(select sum(score) from student where student_name=@student_name) as 总成绩
	,(select count(*) from student where student_name=@student_name) as 学了几门课程
	from student where student_name=@student_name;

--调用存储过程,并传入参数
exec proc_01 '张三';

四、总结下,这是我写的第一篇文章,很浅显、简单。不如其他各位大牛所写的文章有深度。这篇文章也是针对初次接触sql 的学者的,只是我结合自身所理解的东西分享给大家,学无止境,如果有错误的地方欢迎指出,谢谢。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值