trouble with CASE statement

  • hi, i'm having trouble with this for some reason:

    there are five options in this field, they are:

    A

    B

    C

    D

    E

    i made a variable @var

    when the user sets @var = A then it should return A and B

    when the user sets @var = B then it should return B

    when the user sets @var = C then it should return C

    when the user sets @var = D then it should return D

    when the user sets @var = E then it should return E

    how can I do this?

    thanks!!

    -martin

  • i got it guys, the answer for those searching later is:

    and

    (

    [FIELD] = case

    when @var = A then A

    when @var = B then B

    when @var = C then C

    when @var = D then D

    when @var = E then E end

    or

    [FIELD] = case

    when @var = A then B

    when @var = B then B

    when @var = C then C

    when @var = D then D

    when @var = E then E end

    )

    ---------------------------

    thanks for any time spent on this.

    -m

  • If you only have these cases, then I would do this:

    IF @var <> 'A'

    BEGIN

    SELECT whatever

    FROM table

    WHERE [field]=@var

    END

    ELSE

    BEGIN

    SELECT whatever

    FROM table

    WHERE [field]='A' OR [field]='B'

    Of course, you could flip those if you wanted, depending on how you expect the future of the request to go.

    Jared
    CE - Microsoft

  • SELECT whatever

    FROM table

    WHERE [field]=@var

    UNION ALL

    SELECT whatever

    FROM table

    WHERE @var = 'A' and field = 'B'


    [font="Arial"]Low-hanging fruit picker and defender of the moggies[/font]

    For better assistance in answering your questions, please read this[/url].


    Understanding and using APPLY, (I)[/url] and (II)[/url] Paul White[/url]

    Hidden RBAR: Triangular Joins[/url] / The "Numbers" or "Tally" Table: What it is and how it replaces a loop[/url] Jeff Moden[/url]

  • ChrisM@home (6/26/2012)


    SELECT whatever

    FROM table

    WHERE [field]=@var

    UNION ALL

    SELECT whatever

    FROM table

    WHERE @var = 'A' and field = 'B'

    Nicely done... 🙂

    Jared
    CE - Microsoft

  • You can also use a structure like this:

    WHERE 1 = CASE

    WHEN @var = A AND [column] IN (A, B) THEN 1

    WHEN [column] = @var THEN 1

    ELSE 0

    END

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

Viewing 6 posts - 1 through 5 (of 5 total)

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