I have a simple query that I am trying to adapt to a new situation. For this situation, if the variable locationID=1 then I need all records, regardless of its locationID.
However, if it is not equal to 1, I need to only provide records that match that of the @locationID.
Here is my setup example:
DECLARE @locationID INT = 1; -- All Results Regardless of locationID
--DECLARE @locationID INT = 2; -- Only results that match this locationID (2)
--DECLARE @locationID INT = 3; -- Only results that match this locationID (3)
-- Temp Data
DECLARE @temp AS TABLE (color VARCHAR(10), locationID INT, name VARCHAR(20))
INSERT INTO @temp( color, locationID, name )VALUES ( 'Blue', 1, 'Test 1' )
INSERT INTO @temp( color, locationID, name ) VALUES ( 'Red', 2, 'Test 2' )
INSERT INTO @temp( color, locationID, name ) VALUES ( 'Red', 1, 'Test 3' )
INSERT INTO @temp( color, locationID, name ) VALUES ( 'Red', 2, 'Test 4' )
INSERT INTO @temp( color, locationID, name ) VALUES ( 'Red', 3, 'Test 5' )
-- Query
SELECT *
FROM @temp
WHERE
locationID = ...
I am trying to figure out if I need to use a CASE WHEN or some other method for this.