T-SQL:case和while语句

--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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值