locked
Is it possible to use IF ELSE in the middle of WHERE Clause of StoredProcedure RRS feed

  • Question

  • Hi MSDN,

    Is it possible to use condition (if-else) in the middle of WHERE Clause of StoredProcedure ?

    i.e.

    @refNo int , @targetNo int
    AS
    SELECT * FROM Batch WHERE BatchNo = @targetNo
         IF @refNo > 10
               AND BatchNo = @refNo
         ELSE
               AND  BatchNo < @refNo

    Please give me some advice

    Thank you

    SweNz

    ps. SQL SERVER 2005

    • Edited by SweNz Wednesday, March 14, 2012 4:04 PM
    Wednesday, March 14, 2012 4:02 PM

Answers

  • Try this:

    SELECT * FROM Batch
    WHERE BatchNo = @targetNo AND ((@refNo > 10 AND BatchNo = @refNo) OR (@refNo <= 10 AND BatchNo < @refNo))

    David.

    • Proposed as answer by Adam Haines Wednesday, March 14, 2012 4:51 PM
    • Marked as answer by KJian_ Wednesday, March 21, 2012 3:31 AM
    Wednesday, March 14, 2012 4:06 PM

All replies

  • @refNo int , @targetNo int
    AS
    SELECT * FROM Batch
    WHERE BatchNo = @targetNo
    AND ((@refNo > 10 AND BatchNo = @refNo)
     OR  BatchNo < @refNo)
    • Proposed as answer by Vinay Valeti Wednesday, March 14, 2012 4:08 PM
    • Unproposed as answer by Vinay Valeti Wednesday, March 14, 2012 4:09 PM
    Wednesday, March 14, 2012 4:04 PM
  • For conditional where use Case expression

    Thanks and regards, Rishabh , Microsoft Community Contributor

    Wednesday, March 14, 2012 4:06 PM
  • Try this:

    SELECT * FROM Batch
    WHERE BatchNo = @targetNo AND ((@refNo > 10 AND BatchNo = @refNo) OR (@refNo <= 10 AND BatchNo < @refNo))

    David.

    • Proposed as answer by Adam Haines Wednesday, March 14, 2012 4:51 PM
    • Marked as answer by KJian_ Wednesday, March 21, 2012 3:31 AM
    Wednesday, March 14, 2012 4:06 PM
  • Thanks a lot David , Rishabh  , oldjeep

    I got and idea and will try tomorrow (midnight here)

    goodnight then :)

    Wednesday, March 14, 2012 4:54 PM