局部变量的定义
declare @变量名 数据类型
赋值方法
set @变量名=值 或 select @变量名=值
set和select比较
使用场景 | set | select |
---|---|---|
同时对多个变量赋值 | 不支持 | 支持 |
表达式返回多个值 | 错误 | 将返回的最后一个值赋值给变量 |
表达式未返回值时 | 变量被赋NULL值 | 变量保持原型 |
常用全局变量
print '服务器名称:'+@@servername
print 'SQLServer的版本:'+@@version
select @@SERVERNAME as '服务器名称'
select @@VERSION as 'SQLServer的版本'
--获取最后一条SQL语句的执行错误号(547:外键约束相关)
print @@error --值大于0表示最近一个SQL语句执行失败的错误号
数据类型转换
CONVERT(数据类型,表达式,样式) --第三个参数可以省略,一般用于日期类型或浮点类型转字符类型
CAST(表达式 AS 数据类型)
datediff函数计算两个日期之差(查年龄)
--定义变量
declare @birthday datetime,@days int,@age int
--查询出生日期
select @birthday=Birthday from Students where StudentId=100003
--计算出生天数
set @days=DATEDIFF(dayofyear,@birthday,getdate())
--计算年龄
set @age=FLOOR(@days/365)
--输出信息
print '100003学员年龄:'+convert(varchar(20),@age)
--直接查询
select FLOOR(DATEDIFF(dayofyear,Birthday,GETDATE())/365) 年龄
from Students where StudentId=100003
逻辑控制语句
IF-ELSE语句
--语法规范(ELSE是可选部分有多条语句才需要BEGIN-END语句块)
IF(条件)
BEGIN
语句
语句
......
END
ELSE
BEGIN
语句
语句
......
END
WHILE语句
--将所有C#成绩不及格的学员加分到60分
declare @CSharp int,@StuId int
while(1=1)
begin
select top 1 @CSharp=CSharp,@StuId=StudentId from ScoreList where CSharp<60
if(@CSharp<60)
update ScoreList set CSharp=CSharp+1 where StudentId=@StuId
if((select COUNT(*) from ScoreList where CSharp<60)=0)
break
end
CASE-END语句
--学员成绩评级
select 学号=StudentId,
总评=case
when(CSharp+SQLServerDB)/2>=90 then 'A'
when(CSharp+SQLServerDB)/2>=80 then 'B'
when(CSharp+SQLServerDB)/2>=70 then 'C'
when(CSharp+SQLServerDB)/2>=60 then 'D'
else '不及格'
end
from ScoreList