SQL SQL中的无表达式CASE中有多个WHEN?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/582514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple WHEN inside no-expression CASE in SQL?
提问by MetaGuru
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 吗?
回答by Joel Coehoorn
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.
格式可能只是一个降价小故障,但(select...)
在您的示例中,应该是一个更简单的片段。
回答by JoshBerke
回答by Ken Gee
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 语句)