Case Else logic question

  • I have a case statement in my where clause. I'm querying a table for people of a certain gender. When one thing is true, I want only women, when another, I want only men. But in the else case, I want people of both genders. I can't seem to accomplish this else part. Any ideas?

     

    Thanks.

  • Something like the following may work:

    create table testtable (

        SomeID       varchar(10),

        Gender       varchar(1)

    )

    INSERT INTO TestTable (SomeID, Gender)

    SELECT 'RED', 'M' UNION

    SELECT 'BLUE', 'M' UNION

    SELECT 'YELLOW', 'F' UNION

    SELECT 'GREEN', 'F'

    DECLARE @Preference VARCHAR (1)

    SET @Preference = 'F' -- or 'M' or 'B'

    select *

     from TestTable

     where gender =

            case

            when @Preference = 'M' then 'M'

            when @Preference = 'F' then 'F'

            else gender

            end

    Have a great day!

    Wayne

     

  • This should give you an idea of how you can solve it. Execute in Northwind:

    SELECT *

    FROM dbo.Employees

    WHERE Country =

    CASE

    WHEN Title LIKE 'Sales%' THEN 'UK'

    WHEN Title LIKE 'Vice%' THEN 'USA'

    ELSE Country

    END

  • Exactly right. Thank you very much!

  • Thanks a lot for your unnecessary scolding. That will be the last time I post here. Thought you guys were trying to HELP programmers regardless of their level. If I'd known I had to be an expert, I wouldn't have posted.

     

  • Melanie,

    We are here to help people of all skill levels, backgrounds etc.  This is an open forum, with global participation, and there are times when some communication may not come across in the manner it was intended.  Sometimes the poster may not be bale to express themsleves in the most appropriate manner.  Having said that, a thick skin is a useful thing to have anytime we post on the web.

    I hope to see you here again, as there is a lot we can all learn from each other.

    Have a great day

    Wayne

  • I too applogize for the remarks that have left you unhappy. Joe could have been more tactfull in his comments, if it is really him. Post here anytime and hopefully you will have a better experience for an other questions you may have.

     

    I think as a group we would prefer Mr. Celko's comments, even when relavent, to be just on the topic and that no interjection of personal oppinion of the requester or other posters be left out, unless they can be friendly in speech. (Anyone disagree?)

  • hi 

    melanie  send  me  the  code  what  you  have  written

    then  i  can  help  you  with

    case  else  logic  Q

    regards 

    ardent

  • Thanks but it was resolved the same day posted. Appreciate your reply.

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply