T-SQL CASE WHEN 使用小例
用一个SQL语句完成以下查询,从book表中查询出price,当price在10到20之间(包含10和20)时返回“10 to 20”,当price为空返回“Unknown”,其他情况返回原price的值
select case when CONVERT(int, price)>=10 and CONVERT(int, price)<=20 then '10 to 20' when price is null then 'Unknown' else price end as myPrice from Book
或者
select 'myPrice'= case when CONVERT(int, price)>=10 and CONVERT(int, price)<=30 then '10 to 20' when price is null then 'Unknown' else price end from Book
附:
CASE和IF的区别:
在高级语言中,CASE的可以用IF来替代,但是在SQL中不行。
CASE是SQL标准定义的,IF是数据库系统的扩展。
CASE可以用于SQL语句和SQL存储过程、触发器,IF只能用于存储过程和触发器。
在SQL过程和触发器中,用IF替代CASE代价都相当的高,相当的麻烦,难以实现。
在SQL SERVER中,cast和convert函数都可用于类型转换,其功能是相同的,只是语法不同.cast一般更容易使用,convert的优点是可以格式化日期和数值.
select CAST('123.4' as int) select CONVERT(int, '123.4') -- Conversion failed when converting the varchar value '123.4' to data type int.

浙公网安备 33010602011771号