Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL - Case When w/ more than one condition

Author  Topic 

ugh3012
Yak Posting Veteran

62 Posts

Posted - 2014-08-21 : 15:07:27

Is it possible to have more than one conditions per line? Example below. It works fine if I do this, "When 'M" then 'Yes' But, I am trying to have it to check for more than one. The below example does not work. What can I do to do something like this.

SELECT
FirstName, LastName,
CASE WorkCode
WHEN 'M', 'E', 'F' THEN 'Yes'
WHEN 'C', 'D' THEN 'No'
END
FROM Employees

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-08-21 : 15:09:40
[code]

Posted - 08/21/2014 : 15:07:27 Show Profile Email Poster Reply with Quote

Is it possible to have more than one conditions per line? Example below. It works fine if I do this, "When 'M" then 'Yes' But, I am trying to have it to check for more than one. The below example does not work. What can I do to do something like this.

SELECT
FirstName, LastName,
CASE
WHEN WorkCode in ('M', 'E', 'F') THEN 'Yes'
WHEN WorkCode in ('C', 'D') THEN 'No'
END
FROM Employees
[/code]
Go to Top of Page

ugh3012
Yak Posting Veteran

62 Posts

Posted - 2014-08-21 : 15:16:02
quote:
Originally posted by gbritton



Posted - 08/21/2014 : 15:07:27 Show Profile Email Poster Reply with Quote

Is it possible to have more than one conditions per line? Example below. It works fine if I do this, "When 'M" then 'Yes' But, I am trying to have it to check for more than one. The below example does not work. What can I do to do something like this.

SELECT
FirstName, LastName,
CASE
WHEN WorkCode in ('M', 'E', 'F') THEN 'Yes'
WHEN WorkCode in ('C', 'D') THEN 'No'
END
FROM Employees




That did not work. I get a red squiggly line under the comma between M and E. The error message is "Incorrect syntax near ','"
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-08-21 : 15:20:37
Works for me.

Here's a working query. I just executed it, then copied and pasted it here:


SELECT
FirstName, LastName,
CASE
WHEN WorkCode in ('M', 'E', 'F') THEN 'Yes'
WHEN WorkCode in ('C', 'D') THEN 'No'
END
FROM (values ('a','b','M')) v(Firstname, Lastname, Workcode)


copy and paste this into ssms. It should work.

PS. you're running this on SQL Server, right? Which version?
Go to Top of Page

ugh3012
Yak Posting Veteran

62 Posts

Posted - 2014-08-21 : 15:25:33
ohhh. I see what you did. You moved the WorkCode down to each when line. My bad. Many thanks.
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-08-21 : 15:27:10
Copy/paste is your friend!
Go to Top of Page
   

- Advertisement -