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
相关推荐
2401_832365527 分钟前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
2301_7796224124 分钟前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python
2301_7662834436 分钟前
c++如何将控制台输出保存到文件_cout重定向到txt【详解】
jvm·数据库·python
北极的冰箱39 分钟前
MySQL Ver 8.0.41 for macos14.7密码遗忘
数据库·mysql
XDH_CS1 小时前
MySQL 8.0 安装与 MySQL Workbench 使用全流程(超详细教程)
开发语言·数据库·mysql
treacle田2 小时前
达梦数据库-统计信息收集-记录
数据库·达梦数据库统计信息收集
审判长烧鸡2 小时前
PostgreSQL之索引/函数/触发器
数据库·postgresql·触发器·函数·索引
Data_Journal3 小时前
如何使用cURL更改User Agent
大数据·服务器·前端·javascript·数据库
Python私教3 小时前
GenericAgent PySide6 桌面应用深度解析:悬浮按钮 + 聊天面板的原生 Qt 方案
开发语言·数据库·qt
byoass3 小时前
企业云盘与设计软件深度集成:AutoCAD/Revit/SolidWorks插件开发与API集成实战
服务器·网络·数据库·安全·oracle·云计算