T-SQL 高阶语法之存储过程

一:存储过程概念

预先存储好的sql程序,通过名称和参数进行执行,供应程序去调用,也可以有返回结果,存储过程可以包含sql语句

可以包含流程控制、逻辑语句等。

二:存储过程的优点

执行速度更快

允许模块化程序设计

提高系统安全性

减少网络流通量

三:存储过程的分类

1 系统提供的存储过程:名称一般都是以sp_开头,由SQLServer创建、管理和使用,存放在master数据库中。

2 扩展存储过程:名称一般都是以xp_开头,使用编程语言C#创建外部的存储过程,以DLL扩展集的形式存在

3 自定义存储过程:用户在自己的数据库中创建的存储过程

四:常用系统存储过程:

1 列出有关指定数据库或者所有的数据库信息

exec sp_helpdb SMDB

2 更改数据库名字,@newname 参数1 新名字; @dbname 参数2 旧名称

别同时改一个数据库名称

exec sp_renamedb @newname='p',@dbname='Phone'

3 返回某个表列的信息

exec sp_columns Students

4 查看一个表的约束信息

exec sp_helpconstraint Students

5 查看表的所有信息

exec sp_help Students

6 查看某个表的索引信息

exec sp_helpindex Students

五:自定义存储 的语法

create procedure 过程名

-- @参数1 数据类型

-- @参数2 数据类型

--as

-- sql语句

--go

六:关于自定义存储 的例子

一:创建一个存储过程。查询考试成绩,显示学号姓名或者班级总成绩,并按照成绩总分高低排序

-- 统计分析考试成绩,显示班级名称 C#平均分 数据库平均分 按照班级的分组来进行实现

sql 复制代码
use SMDB
 go

 -- 如果已经存在 usp_test1存储过程 就先删除这个存储过程
 if exists(select * from sysobjects where name ='usp_test1')
 drop procedure usp_tes1
 go

 -- 定义存储过程
 create procedure usp_tes1
 as 
	 -- sql语句
	 -- 查询考试成绩,显示学号姓名班级总成绩,并按照成绩总分高低排序
	select Students.StudentId,StudentName,ClassName,总成绩 = (CSharp + SqlserverDB) from Students
	inner join StudentClass on StudentClass.ClassId = Students.ClassId
	inner join ScoreList on ScoreList.StudentId = Students.StudentId
	order by 总成绩 DESC

	-- 统计考试成绩,显示班级名称 C#平均分 按照班级分组进行实现
	select ClassName,CSharp平均分=AVG(CSharp),数据库平均分 = AVG(SqlserverDB) from ScoreList
	inner join Students on ScoreList.StudentId = ScoreList.StudentId
	inner join StudentClass on StudentClass.ClassId = Students.ClassId
	group by ClassName
	order by ClassName
	
 go

 -- 调用存储过程
 exec usp_tes1
二:带参数的存储过程

查询考试成绩要求能够按照自定义的及格线查询结果?

sql 复制代码
 use SMDB
 go

 create procedure usp_test2
	 -- 输入参数
	 @cs int,-- csharp 及格线
	 @db int -- 数据库及格线
as 
	select Students.StudentId,StudentName,CSharp,SqlserverDB from ScoreList
	inner join Students on Students.StudentId = ScoreList.StudentId
	where SqlserverDB > @cs

	select Students.StudentId,StudentName,CSharp,SqlserverDB from ScoreList
	inner join Students on Students.StudentId = ScoreList.StudentId
	where SqlserverDB > @db
go 

exec usp_test2 68,80
exec usp_test2 @cs = 50,@db = 70
exec usp_test2 @db = 70,@cs = 50
相关推荐
SelectDB12 小时前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶13 小时前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵16 小时前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
Nturmoils17 小时前
WHERE 条件别凭习惯写,常用查询先跑一遍
数据库
Databend2 天前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
ClouGence3 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
飞将3 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils4 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波4 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_5 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库