一、直接附上代码,简单易懂
---------------------------------------------前提代码-----------------------------------------------------------------
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 的学者的,只是我结合自身所理解的东西分享给大家,学无止境,如果有错误的地方欢迎指出,谢谢。