当前位置:网站首页>[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)
[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)
2022-08-05 05:38:00 【takedachia】
工具:SQL Server 2019 Express
操作系统:Windows 10
文章目录
Database backup used: teaching.bak
Review the table structure:
t_student (S#, Sname, Sex, Age, Major)
t_teacher (T#, Tname, Age, Title)
t_course (C#, Cname, T#)
t_student_course (S#, C#, Score)
关于T-SQL
T-SQL,即 Transact-SQL,是SQL Server对标准SQL语言的扩充.
我们在SQL Server上使用的SQLLanguage can be understood as an enhanced versionsql,Not only all standards are supportedSQL语言操作,At the same time, there are many functional extensions(Include variables and flow control statements).
定义变量
变量分全局变量和局部变量.
Global variables are preset by the system,均以@@开头,如@@error,可用select @@变量名直接调用,不详述.
局部变量以@开头,通过 DECLARE 关键字定义:
DECLARE @变量名 数据类型
定义完后,通过SELECT或SET关键字给变量赋值:
SET(SELECT) @变量名 = ...
例1:
declare @CurrentDateTime char(30)
set @CurrentDateTime = GETDATE()
select @CurrentDateTime as '当前的日期和时间'
go
上面的 go 是批处理的结束符,Indicates that the above three sentences are packaged and sent to the processor(服务器)进行处理.
注意:A variable is only valid within the batch in which it is defined.If the above three sentences are executed individually in turn,Go to the second sentencesetIt will give an error message when there is [email protected]这个变量.
上例结果:
例2(With flow control):
declare @Exp1 int, @Exp2 int
set @Exp1 = 30
set @Exp2 = 50
if @Exp1>@Exp2
select @Exp2 as 较小数
else
select @Exp1 as 较小数
结果:
例3(字符串相加 “+”):
declare @ResultStr char(60)
select @ResultStr='hello'+'world'
select @ResultStr as String concatenation result
结果:
T-SQL中的查询
我们在使用T-SQL的查询时,一般先用 USE The keyword selects the current database,后接GO,语法:
USE 数据库名
GO
SELECT...
The following are some commonly used advanced query methods.
Return to the previous items(TOP)
例①:浏览 t_student 表前3项
use TeachingDB_new
go
select top 3 *
from t_student

例②:浏览 t_student 表50%的项
use TeachingDB_new
go
select top 50 percent *
from t_student

汇总统计(WITH CUBE)
我们之前学过 group by 用于将数据分组,Statistics are then calculated for each group.
在T-SQL中,group by可以于 WITH CUBE、WITH ROLLUP 联合使用,Implement more statistical functions.
例:
We already have a statistic for the grade sheet:
我们加上 WITH CUBE,进行汇总统计:
select C#, avg(Score) as 平均成绩, count(S#) as 选修人数
from t_student_course
group by C#
with cube

with cube In addition to the statistics row for each grouping,A summary row is also provided.
当group byWhen grouping by a single attribute,with cube Adds a summary row to the query result,Summarized rows appear as values on the grouping attribute“NULL”,并且Statistics are performed on all records without grouping.
流程控制
SET
SET:为局部变量赋值,如前所述
语句块(BEGIN…END)
BEGIN…END将多个T-SQLStatements are grouped into statement blocks,并将它们视为一个单元处理.
语法:
BEGIN
T-SQL语句
T-SQL语句
......
END
条件分支(IF…ELSE)
"定义变量"的例2shown in.语法:
IF 条件表达式
T-SQL语句(或BEGIN...END语句块)
ELSE
T-SQL语句(或BEGIN...END语句块)
其中,The value of the conditional expression is a logical value.
Conditional expressions can containselect语句,需要用括号()括起来.
if…else可嵌套.
例:
if exists(select * from t_student_course where S#='2012001')
select avg(Score) from t_student_course where S#='2012001'
else
print 'There is no course selection record for this student'

多分支(CASE)
case与end相接.
在case语句中,对caseThe following expression is evaluated,Find the first matching value from top to bottomwhen子句,获取thenthe corresponding value after.
caseAn expression is an example of a lookup expression,It can itself be used for conditional assignment.
例1、MajorColumns are divided into broad categories:
select S#, Sname,
case Major
when '软件工程' then '工科专业'
when '机械电子' then '工科专业'
else '文科专业'
end as '专业类别'
from t_student

例2、新建一列,判断成绩级别:
select S#, C#,
case
when Score>=90 then 'A'
when Score>=80 then 'B'
when Score>=70 then 'C'
else 'D'
end as 成绩级别
from t_student_course

重复执行(WHILE)
while:Execute a statement repeatedly(块),语法:
WHILE 条件表达式
T-SQL语句(或BEGIN...END语句块)
在循环中,使用 BREAK 跳出循环,也可以用 CONTINUE 继续下一循环.
while循环可以嵌套.
例:累加,到大于1000显示结果:
declare @i int, @a int
set @i=1
set @a=0
while @i <= 100
begin
set @a = @a + @i
if @a >= 1000 break
set @i = @i + 1
end
select @a as 'a', @i as 'i'

边栏推荐
猜你喜欢

IJCAI 2022|边界引导的伪装目标检测模型BGNet

哥廷根大学提出CLIPSeg,能同时作三个分割任务的模型

【22李宏毅机器学习】课程大纲概述
![[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)](/img/ac/884d8aba8b9d363e3b9ae6de33d5a4.png)
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)

【Kaggle项目实战记录】一个图片分类项目的步骤和思路分享——以树叶分类为例(用Pytorch)

CAP+BASE

flink on yarn 集群模式启动报错及解决方案汇总

【数据库和SQL学习笔记】3.数据操纵语言(DML)、SELECT查询初阶用法

【Pytorch学习笔记】9.分类器的分类结果如何评估——使用混淆矩阵、F1-score、ROC曲线、PR曲线等(以Softmax二分类为例)

Flink Table API 和 SQL之概述
随机推荐
【论文精读】ROC和PR曲线的关系(The relationship between Precision-Recall and ROC curves)
【数据库和SQL学习笔记】9.(T-SQL语言)定义变量、高级查询、流程控制(条件、循环等)
大型Web网站高并发架构方案
AIDL详解
6k+ star,面向小白的深度学习代码库!一行代码实现所有Attention机制!
BFC详解(Block Formmating Context)
读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping
ES6基础语法
如何编写一个优雅的Shell脚本(三)
MySQL
原来何恺明提出的MAE还是一种数据增强
学习总结week2_1
Tensorflow踩坑笔记,记录各种报错和解决方法
CVPR最佳论文得主清华黄高团队提出首篇动态网络综述
flink项目开发-配置jar依赖,连接器,类库
【数据库和SQL学习笔记】10.(T-SQL语言)函数、存储过程、触发器
SparkML-初探-文本分类
学习总结week2_2
如何跟踪网络路由链路&检测网络健康状况
Spark ML学习相关资料整理