sql query where parameters null not null

Posted by Laziale on Stack Overflow See other posts from Stack Overflow or by Laziale
Published on 2013-10-23T15:42:50Z Indexed on 2013/10/23 15:53 UTC
Read the original article Hit count: 214

I am trying to do a sql query and to build the where condition dynamically depending if the parameters are null or no. I have something like this:

SELECT tblOrder.ProdOrder, tblOrder.Customer FROM tblOrder 
CASE WHEN @OrderId IS NOT NULL
THEN 
WHERE tblOrder.OrderId = @OrderId
ELSE
END
CASE WHEN @OrderCustomer IS NOT NULL
THEN
AND tblOrder.OrderCustomer = @OrderCustomer
ELSE
END
END

This doesn't work, but this is just a small prototype how to assemble the query, so if the orderid is not null include in the where clause, or if the ordercustomer is not null include in the where clause. But I see problem here, for example if the ordercustomer is not null but the orderid is null, there will be error because the where keyword is not included. Any advice how I can tackle this problem. Thanks in advance, Laziale

© Stack Overflow or respective owner

Related posts about sql

Related posts about sql-server-2008