SQL知识二(Day 27)
时间:2022-03-14 03:52
大家好,好几天都没写博客了。因为自己的一些原因,落下了很多。今天没有学什么新的知识,自己就把以前落下的好好看了一下。好了,今天就先总结一下SQL剩下的一些知识吧。
主要学的知识有:循环语句(case语句,if else语句,while语句),跳转语句(break, continue),存储过程,视图,索引,触发器的创建与简单运用。
循环语句:
case语句
输入学生的成绩 1-100之间,否则就会提示"您输入的成绩不对,成绩应该在0-100之间"
declare @cj float,@str varchar(50) set @cj=90 set @str= case --case [表达式] when @cj>100 or @cj<0 then ‘成绩不对,应该在0——100之间‘ -- when 条件表达式1 then 结果1 when @cj>=60 and @cj<70 then ‘及格‘ -- when 条件表达式2 then 结果2 when @cj>=70 and @cj<80 then ‘中等‘ -- ........ when @cj>=80 and @cj<90 then ‘优良‘ when @cj>=90 and @cj<=100 then ‘优秀‘ else -- else ‘成绩不及格‘ end print ‘该学生的成绩评语是‘+@str --输出
查找出不同仓库的平均工资
select *,不同仓库的平均工资= case when 仓库号=‘wh1‘ then (select AVG(工资) from 职工 where 仓库号=‘wh1‘) when 仓库号=‘wh2‘ then (select AVG(工资) from 职工 where 仓库号=‘wh2‘) when 仓库号=‘wh3‘ then (select AVG(工资) from 职工 where 仓库号=‘wh3‘) when 仓库号=‘wh4‘ then (select AVG(工资) from 职工 where 仓库号=‘wh4‘) end from 职工
结果:
while语句 计算0——100之间的和
--while 条件表达式 -- begin --命令行或程序 -- end declare @num int, @sum int select @num=0,@sum=0 while @num<=100 begin set @sum=@sum+@num set @num=@num+1 end print ‘1-100之间的和是:‘+cast(@sum as varchar(50))
if else语句
某地到青岛的邮政里程为1043,通过邮政局向青岛城区交 "特征专递"邮件, 24小时之内达到。计费每克0.12元
但超过100克,超过数量每克0.05元,算出邮费
declare @yf real,@weight int --声明变量 set @weight=120 if @weight<=100 begin set @yf=@weight*0.12 end else begin set @yf=100*0.12+(@weight-100)*0.05 end --输出邮件的重量和邮费 print‘邮件的重量是‘+cast(@weight as varchar(50)) print ‘邮费是‘+cast(@yf as varchar(50))
结果:
用户登录
declare @name varchar(50),@pwd varchar(50),@msg varchar(50) --定义变量 select @name=‘admin‘,@pwd=‘123456‘ if @name=‘admin‘ and @pwd=‘1256‘ begin set @msg=‘用户登录成功!‘ end else begin set @msg=‘用户登录失败,请重新登录!‘ end print @msg
跳转语句
break语句
--break 语句 declare @num int,@sum int select @num=0,@sum=0 while @num<=10 begin set @num=@num+1 set @sum=@sum+@num if @sum>30 --当sum和大于30时,跳出整个循环语句 break end print ‘最后结果‘+cast(@sum as varchar(50))
结果:
continue语句
--continue语句 declare @x int,@sums int select @x=0,@sums=0 while @x<=100 begin set @x=@x+1 if @x%2=1 continue --跳出当前循环,进行下一个循环 set @sums=@sums+@x end print ‘偶数和‘+cast(@sums as varchar(50))
视图
存储过程
索引
在sql中,讲SQL语句组成一个事物,其目的是保证这一组sql语句能够得到可靠地执行,如果系统中出现了错误,阻碍sql的执行,并且只要其中任何一条语句出现错误,事物中所有的sql语句都不会被执行,说白了要么全部sql执行,要么全部不执行。
create unique index unique_index on 仓库(仓库号) --创建索引
触发器
触发器是一种特殊的存贮过程,他就相当于c#中的事件触发器主要是通过事件触发而被执行的
create trigger 触发器名称 on 表 for insert[update,delete] as
begin
程序块
end
好了,今天就先写到这里吧,其实对于触发器还是有一些不明白,课下我会好好看些资料,请教下其他人,等我弄明白后再总结一下吧。加油!