20

我几乎可以肯定您不能在案例陈述的上下文中执行此操作,并且我无法找到任何有关它的文档,但是否可以执行以下操作:

SELECT CASE WHEN testValue > 2 
THEN testValue(Without Repeating it) ELSE FailValue)
END 
FROM Table 

一个更好更彻底的例子:

Select CASE WHEN (Foo-stuff+bar) > 2 
THEN Conditional statement without >2 Else "Fail"
END 
FROM TABLE

我正在寻找一种无需重复条件查询即可创建选择的方法。

编辑:由于我的例子很差,而且我正在寻找的答案缺乏:

testValue = (Table.A / Table.B) * Table.C Table.D

SELECT CASE WHEN testValue > 2 
THEN testValue ELSE FailValue)
END 
FROM Table 
4

4 回答 4

20

Like so

DECLARE @t INT=1

SELECT CASE
            WHEN @t>0 THEN
                CASE
                    WHEN @t=1 THEN 'one'
                    ELSE 'not one'
                END
            ELSE 'less than one'
        END

EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.

于 2013-10-07T19:40:22.140 回答
19

查询可以写得稍微简单一些,像这样:

DECLARE @T INT = 2 

SELECT CASE 
         WHEN @T < 1 THEN 'less than one' 
         WHEN @T = 1 THEN 'one' 
         ELSE 'greater than one' 
       END T
于 2013-10-07T19:46:12.973 回答
2

我正在寻找一种无需重复条件查询即可创建选择的方法。

我假设你不想重复Foo-stuff+bar。您可以将计算放入派生表中:

SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END 
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a

一个公用表表达式也可以工作:

WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END    
FROM a

此外,您的开关的每个部分都应返回相同的数据类型,因此您可能必须转换一个或多个案例。

于 2013-10-07T19:52:05.523 回答
0

我们可以像这样使用case语句

select Name,EmailId,gender=case 
when gender='M' then 'F'
when gender='F' then 'M'
end
 from [dbo].[Employees]

我们也可以如下。

select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
 from [dbo].[Employees]
于 2016-07-28T11:33:56.800 回答