With the following code:
CREATE TABLE #MyTable
(
PartNum VARCHAR(20),
PartColor VARCHAR(100)
)
INSERT INTO #MyTable
VALUES
('00039','Blue'),
('00039','Red'),
('01234','Blue'),
('23456','Red')
CREATE TABLE #Variables
(
VarName VARCHAR(20),
Value VARCHAR(100)
)
INSERT INTO #Variables VALUES
('PartNum', '00039'),
('PartColor', NULL)
SELECT *
FROM MyTable
WHERE PartNum = (SELECT Value FROM #Variables WHERE VarName = 'PartNum')
AND PartColor = (SELECT Value FROM #Variables WHERE VarName = 'PartColor')
If PartColor is NULL, that part of the WHERE clause should be ignored and all records should be returned regardless of PartColor (assuming PartNum = 00039)
I know I can do it this way:
DECLARE @PartNum VARCHAR(20) = '00039'
@PartColor VARCHAR(100) = NULL
SET @PartColor = ISNULL(@PartColor, '-1')
SELECT *
FROM MyTable
WHERE PartNum = @PartNum
AND PartColor IN (SELECT (@PartColor) OR @PartColor = '-1')
However, I was playing around with putting variables in a table and not sure how to achieve the same result.
I tried using this but the query returned 0 results:
AND PartColor IN ((SELECT Value from #Variables where VarName = 'PartColor'
OR (SELECT ISNULL(Value, '-1') from #Variables where VarName = 'PartColor') = '-1'))
I'm pretty sure I can't check for a value that way
This was an idea but the syntax isn't valid:
AND PartColor IN ((SELECT Value from #Variables where VarName = 'PartColor')
OR (SELECT Value from #Variables where VarName = 'PartColor') IS NULL)