简体   繁体   中英

SQL Server - Case Statement

I'm almost certain you cannot do this within the context of the case statement, and I haven't been able to find any documentation about it, but is it possible to do the following:

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

A better more thorough example:

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

I am looking for a way to create a select without repeating the conditional query.

EDIT: Due to a poor example on my part, and the lack of answers I was looking for:

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

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

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.

The query can be written slightly simpler, like this:

DECLARE @T INT = 2 

SELECT CASE 
         WHEN @T < 1 THEN 'less than one' 
         WHEN @T = 1 THEN 'one' 
         ELSE 'greater than one' 
       END T

I am looking for a way to create a select without repeating the conditional query.

I'm assuming that you don't want to repeat Foo-stuff+bar . You could put your calculation into a derived table:

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

A common table expression would work just as well:

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

Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.

We can use case statement Like this

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

WE can also it as follow.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM