当前位置:网站首页>[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'

边栏推荐
猜你喜欢

发顶会顶刊论文,你应该这样写作

原来何恺明提出的MAE还是一种数据增强

华科提出首个用于伪装实例分割的一阶段框架OSFormer

【论文阅读-表情捕捉】ExpNet: Landmark-Free, Deep, 3D Facial Expressions

CVPR最佳论文得主清华黄高团队提出首篇动态网络综述

MaskDistill - Semantic segmentation without labeled data

flink部署操作-flink on yarn集群安装部署

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

【论文精读】R-CNN 之预测框回归(Bounding box regression)问题详述

【数据库和SQL学习笔记】9.(T-SQL语言)定义变量、高级查询、流程控制(条件、循环等)
随机推荐
day8字典作业
学习总结week2_2
Day1:用原生JS把你的设备变成一台架子鼓!
AWS 常用服务
MySQL
HQL statement execution process
【论文精读】ROC和PR曲线的关系(The relationship between Precision-Recall and ROC curves)
盘点关于发顶会顶刊论文,你需要知道写作上的这些事情!
【22李宏毅机器学习】课程大纲概述
flink on yarn 集群模式启动报错及解决方案汇总
【Pytorch学习笔记】11.取Dataset的子集、给Dataset打乱顺序的方法(使用Subset、random_split)
序列基础练习题
服务网格istio 1.12.x安装
学习总结week2_3
CVPR最佳论文得主清华黄高团队提出首篇动态网络综述
鼠标放上去变成销售效果
A deep learning code base for Xiaobai, one line of code implements 30+ attention mechanisms.
Matplotlib(一)—— 基础
轻松接入Azure AD+Oauth2 实现 SSO
flink部署操作-flink on yarn集群安装部署