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
相关推荐
snow@li3 小时前
数据库:市场中都有哪些数据库 / 优缺点 使用情况
数据库
NoSi EFUL4 小时前
MySQL中ON DUPLICATE KEY UPDATE的介绍与使用、批量更新、存在即更新不存在则插入
android·数据库·mysql
河阿里4 小时前
SQL数据库:五大范式(NF)
数据库·sql·oracle
l1t5 小时前
DeepSeek总结的PostgreSQL 19查询提示功能
数据库·postgresql
chenxu98b6 小时前
MySQL如何执行.sql 文件:详细教学指南
数据库·mysql
刘晨鑫17 小时前
MongoDB数据库应用
数据库·mongodb
梦想的颜色7 小时前
mongoTemplate + Java 增删改查基础介绍
数据结构·数据库·mysql
小小小米粒8 小时前
redis命令集合
数据库·redis·缓存
Irene19918 小时前
SQL 中日期的特殊性总结(格式符严格要求全大写)
sql
herinspace8 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别