[英]Multiple WHEN inside no-expression CASE in SQL?
DECLARE @TestVal int
SET @TestVal = 5
SELECT
CASE
WHEN @TestVal <=3 THEN 'Top 3'
ELSE 'Other'
END
I saw this sample code online but I couldn't find an example where there was no expression and it had more than one WHEN, so I am wondering if this type of thing is OK:我在网上看到了这个示例代码,但是我找不到没有表达式并且它有多个 WHEN 的示例,所以我想知道这种类型的东西是否可以:
DECLARE @TestVal int
SET @TestVal = 5
SELECT
CASE
WHEN @TestVal <=3 THEN 'Top 3'
WHEN (select ...) = 1 THEN 'Other Value'
WHEN (select ...) = 2 THEN 'Other Value 2'
ELSE 'Other'
END
Or do I need to say CASE WHEN for each line?还是我需要为每一行说 CASE WHEN?
Yes, that's fine, but I would line up the "WHEN"s vertically and explain it more like this:是的,这很好,但我会垂直排列“WHEN”并更像这样解释:
SELECT
CASE
WHEN @TestVal <=3 THEN 'Top 3'
WHEN @TestVal <=10 THEN 'Top 10'
WHEN @TestVAl <=25 THEN 'Top 25'
ELSE 'Other'
END
The formatting might just be a markdown glitch, but the (select...)
in your example complicated what should be a simpler snippet.格式可能只是 markdown 故障,但您示例中的
(select...)
使应该是更简单的片段变得复杂。
SELECT
CASE
WHEN @TestVal <=3 THEN 'Top 3'
WHEN @TestVal <=10 THEN 'Top 10'
WHEN @TestVAl <=25 THEN 'Top 25'
ELSE 'Other'
END
In regards to nesting case statements this can be done as well (up until 10 nested case statements allowed within sql)关于嵌套 case 语句,也可以这样做(sql 中最多允许 10 个嵌套 case 语句)
http://msdn.microsoft.com/en-us/library/ms181765.aspx http://msdn.microsoft.com/en-us/library/ms181765.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.