--CASE语法:
--case 输入表达式
--when 表达式1 then 结果1
--when 表达式2 then 结果2
--。。。。。
--else 结果表达式n+1(上面的内容都不满足)
--首先获取“电子产品”类商品的平均库存,将其存放在变量中,
--通过比较‘电子产品’类所有商品和平均库存间的关系得到相应
--的评价。
--(1)声明一个变量存储电子产品类的平均库存
declare @store int
select @store= avg(Store) from
Category,Product
where Category.CategoryID=Product.CategoryID
and CategoryName='电子产品'
--(2)查询电子产品下的所有商品
select ProductName,Store,评价=case
when Store>@store then '库存偏高'
when Store=@store then '库存合理'
else '库存偏低'
end
from Category,Product
where Category.CategoryID=Product.CategoryID
and CategoryName='电子产品'
--查询订单,显示订单编号以及订单状态 0--》未发货
--1-->已发货 2--》已收货
select OrderId as 订单编号,订单状态=case [status]
when 0 then '未发货'
when 1 then '已发货'
when 2 then '已收货'
else '状态编号错误'
end
from [Order]
--循环--案例1 10遍 hello world
--1.先声明变量
declare @i int
--2.赋值
set @i=1while @i<=10
begin
print '第'+convert(nvarchar(20), @i)+'遍:hello world'
--set @i=@i+1
set @i+=1
end
--案例2 打印输出1到10
declare @j int
set @j=1
while @j<=10
begin
print @j
set @j+=1
end
--案例3 打印输出1到100之间的所有偶数和
declare @k int,@sum int
set @k=1
set @sum=0
while @k<=100
begin --判断@k是否是一个偶数
if @k%2=0
begin
set @sum+=@k
end
set @k+=1
end
print '1到100之间的所有偶数和是:'+convert(nvarchar(20),
@sum)
--练习 求出1到100之间能够被3整除的最大数
declare @g int
set @g=100;
while @g<=100
begin
if @g%3=0
begin
print @g
break
end
else
set @g-=1
end