Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use T-SQL's Case/When?

Tags:

tsql

case-when

I have a huge query which uses case/when often. Now I have this SQL here, which does not work.

 (select case when xyz.something = 1  then      'SOMETEXT'  else       (select case when xyz.somethingelse = 1)       then           'SOMEOTHERTEXT'       end)         (select case when xyz.somethingelseagain = 2)       then           'SOMEOTHERTEXTGOESHERE'       end)  end) [ColumnName], 

Whats causing trouble is xyz.somethingelseagain = 2, it says it could not bind that expression. xyz is some alias for a table which is joined further down in the query. Whats wrong here? Removing one of the 2 case/whens corrects that, but I need both of them, probably even more cases.

like image 543
grady Avatar asked Jul 27 '10 09:07

grady


People also ask

How do I use a case statement in the where clause in SQL Server?

Another way to use the Case Statement is within the WHERE clause. There, it may be utilized to alter the data fetched by a query based on a condition. Within that context, the Case Statement is ideally suited to both static queries, as well as dynamic ones, such as those that you would find inside a stored procedure.

How do you put a CASE in a select query?

insert into table table_name ( value1, value 2,value 3) select (value 1,value2 , case value3 when value1 = 'somevalue' &&* value2 = 'somevalue' then 'x' else 'y' End from table_name.


1 Answers

SELECT    CASE     WHEN xyz.something = 1 THEN 'SOMETEXT'    WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'    WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'    ELSE 'SOMETHING UNKNOWN'    END AS ColumnName; 
like image 190
Florian Reischl Avatar answered Oct 03 '22 05:10

Florian Reischl