I have a SQL Server 2008 table with the following structure and data
INSERT INTO [ProductDetails]([ProductID],[ProductName],[Vendor],[Category])
VALUES(1,'Milk','V1','Food')
INSERT INTO [ProductDetails]([ProductID],[ProductName],[Vendor],[Category])
VALUES(2,'Milk','V2','Food')
INSERT INTO [ProductDetails]([ProductID],[ProductName],[Vendor],[Category])
VALUES(3,'Banana','V2','Food')
I want to apply logical OR in my search criteria with the following search parameters
DECLARE @ProductName VARCHAR(10)
DECLARE @Vendor VARCHAR(10)
The expected results are listed below in various scenarios.
---CASE 1
SET @ProductName = NULL
SET @Vendor = NULL
--Expected ProductID = 1,2,3
---CASE 2
SET @ProductName = 'Milk'
SET @Vendor = 'V2'
--Expected ProductID = 1,2,3
---CASE 3
SET @ProductName = NULL
SET @Vendor = 'V2'
--Expected ProductID = 2,3
---CASE 3
SET @ProductName = 'Banana'
SET @Vendor = NULL
--Expected ProductID = 3
---CASE 5
SET @ProductName = 'Banana'
SET @Vendor = 'V2'
--Expected ProductID = 2,3
The only solution, I can think of now, is to run separate queries as follows.
IF both
@ProductName
and@Vendor
areNULL
, select all the productsIF
@ProductName
and@Vendor
are non-null, make a union of two select queries (query based on@ProductName
value and query based on@Vendor
value)IF
@ProductName
isNOT null
and@Vendor
isNULL
, select query result based on@ProductName
valueIF
@ProductName
is null and@Vendor
isNOT null
, select query result based on@Vendor
value.
Is there a better solution that can be done in one query like the one we do for logical AND?
REFERENCE: