栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

sqlservice存储过程的简单使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

sqlservice存储过程的简单使用

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

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

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 的学者的,只是我结合自身所理解的东西分享给大家,学无止境,如果有错误的地方欢迎指出,谢谢。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/758697.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号