--------------------SQL Server2019 常用语法 ------------------------
--------------1,Case end 的用法(和 Oracle 的语法一致)-----------------
- select t.name,
- 'Degree' =
- case
- when t.score>=95 then 'A'
- when t.score>=85 then 'B'
- when t.score>=75 then 'C'
- when t.score>=60 then 'D'
- else 'D-'
- end
- from SCORES t where Catogory = 'English';
--------------1,Case end 的用法 (和 Oracle 的语法一致) 结束 -------------
-------------------2,ROW_NUM() OVER(ORDER BY)用法 --------------------
-- 长用于增加一个编号, 用于数据库分页查询
--over 表示按照某一列进行编号
select 'SYSID' = ROW_NUMBER() OVER (ORDER BY SCOID),* from Scores;
-------------------2,ROW_NUM() OVER(ORDER BY)用法结束 ----------------
---------------------------3, 变量的声明与赋值 ------------------------
-- 声明时直接赋值 declare
- declare @num int = 10;
- print @num
- --select @num
-- 先声明 declare, 再赋值 set
- declare @name nvarchar(10)
- set @name ='JeremyWu'
- print @name
- --select @num
-- 一个例子, 根据分数输出等级
-- 输出等级
- declare @degree nvarchar(10);
- declare @score int;
- set @score = (select avg(Score) from scores where name='Jeremy')
- if (@score>=90)
- begin
- set @degree = 'A'
- end
- else
- begin
- set @degree = 'B'
- end;
- print @degree;
---------------------------3, 变量的声明与赋值结束 --------------------
---------------------------4, 变量的常见类型 --------------------------
-- 局部变量, 我们自己声明的变量
-- 例如:@num
-- 全局变量或者叫做系统变量, 系统声明的变量
-- 例如:@@ERROR
---------------------------4, 变量的常见类型结束 -----------------------
---------------------------------5, 事务 -------------------------------
-- 背景说明: Bank 表中 Money 列右最小值限制, 不能小于 10
--select * from Bank
-- 开始事务
BEGIN TRANSACTION
-- 声明一个变量记录有没有错误发生
declare @sumError int = 0;
-- 执行相关操作
update Bank set Money = Money - 1000 where BankId=2;
-- 记录此时的错误数
set @sumError = @sumError + @@ERROR;
-- 执行相关操作
update Bank set Money = Money + 1000 where BankId=3;
-- 记录此时的错误数
set @sumError = @sumError + @@ERROR;
-- 判断记录的错误数
- if(@sumError <> 0)
- begin
-- 失败了, 回滚事务
- ROLLBACK TRANSACTION
- end
- else
- begin
-- 成功了, 提交事务
- COMMIT TRANSACTION
- end;
-- 打印一下消息
print @sumError
---------------------------------5, 事务结束 ---------------------------
--------------6,Case end 的用法(和 Oracle 的语法一致)------------------
- select t.name,
- 'Degree' =
- case
- when t.score>=95 then 'A'
- when t.score>=85 then 'B'
- when t.score>=75 then 'C'
- when t.score>=60 then 'D'
- else 'D-'
- end
- from SCORES t where Catogory = 'English';
--------------6,Case end 的用法 (和 Oracle 的语法一致) 结束 --------------
作者: Jeremy.Wu https://www.cnblogs.com/jeremywucnblog/
来源: http://www.bubuko.com/infodetail-3458105.html