1

Have stored procedure some like this.

CREATE PROCEDURE test
  @ID
  @inventory bit = 0
  @status nvarchar(2) = null
AS
BEGIN
 SELECT 
   ID
   INVENTORY = (SELECT SUM(Inventory) FROM Option WHERE /*Inventory if 0 with if 1 without*/)
   STATUS
 WHERE 
   --TODO Status if
END

how to create if statement when status can be null, '', 'preordered' for example: if null select all status, if '' select empty status, if some status - select some status. And need to create where condition for Inventory(with/without)

AleksP
  • 1,244
  • 2
  • 12
  • 18
  • Have a look at this question from the other day: http://stackoverflow.com/questions/25414333/best-way-to-do-a-case-where-clause-sql-server/25414390#25414390 – DaveShaw Aug 21 '14 at 21:45

2 Answers2

2

if null select all status, if '' select empty status, if some status - select some status

Just add a check for a null status and don't include any other condition in that case:

WHERE (@status IS NULL) /* ALL */ 
   OR
    (@status = STATUS) /* match status */

If you add a condition for Inventory make sure you put the status check in parentheses. AND gets evaluated before OR so it's best to logically group the conditions so they don't get evaluated out-of-order.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
2
WHERE (@status IS NULL  OR (@status  =STATUS))

Excludes no records if @Status is null

Tom Page
  • 1,211
  • 1
  • 7
  • 8