Sql Query in Case Staement

  • Can we write a Sql Query in the Then Clause of CASE Statement as shown below:

    DECLARE @Type INT

    SET @Type=10

    'Count'=

    CASE

    WHEN @Type=10 THEN SELECT COUNT(ItemId) FROM Item WHERE ....

    WHEN @Type=20 THEN SELECT COUNT(ItemId FROM ItemSupport WHERE ....

    END

    Thanks!!!

  • You very well can, as long as the statement you are using after the THEN clause does not return more than 1 value (1 column 1 row)

  • Yes but you need to encapsulate the SELECT in parenthesis and, as ColdCoffee identified, it must return only 1 value.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Thanks guys for all the responses!!!

Viewing 4 posts - 1 through 3 (of 3 total)

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