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

边栏推荐
猜你喜欢

读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping

【Pytorch学习笔记】10.如何快速创建一个自己的Dataset数据集对象(继承Dataset类并重写对应方法)

Flink Broadcast 广播变量

Matplotlib(三)—— 实践

6k+ star,面向小白的深度学习代码库!一行代码实现所有Attention机制!

SQL(1) - Add, delete, modify and search

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

el-pagination左右箭头替换成文字上一页和下一页

服务网格istio 1.12.x安装

【论文阅读-表情捕捉】ExpNet: Landmark-Free, Deep, 3D Facial Expressions
随机推荐
[After a 12] No record for a whole week
day6-列表作业
CVPR 2022 |节省70%的显存,训练速度提高2倍
Kubernetes常备技能
A deep learning code base for Xiaobai, one line of code implements 30+ attention mechanisms.
flink实例开发-batch批处理实例
Tensorflow2 与 Pytorch 在张量Tensor基础操作方面的对比整理汇总
如何编写一个优雅的Shell脚本(一)
学习总结day5
Flink Broadcast 广播变量
Mysql-连接https域名的Mysql数据源踩的坑
vscode要安装的插件
My 的第一篇博客!!!
BFC(Block Formatting Context)
Service
HQL statement execution process
IDEA 配置连接数据库报错 Server returns invalid timezone. Need to set ‘serverTimezone‘ property.
flink部署操作-flink standalone集群安装部署
周末作业-循环练习题(2)
通过Flink-Sql将Kafka数据写入HDFS