I have a stored procedure that I'm passing 22 string variables to from SSRS. The variables can either be null or be a string. When a Null value is passed to the stored procedure, I need to return all records. While if the a string is passed, I need to filter to only those values. In my example, I'm using string_split and saving the variables into a temporary table.
Drop table if exists #Authors
Drop table if exists #Temp
CREATE TABLE #Authors
(
Id INT PRIMARY KEY,
Names VARCHAR (50) NOT NULL,
)
INSERT INTO #Authors
VALUES (1, 'AuthorA'),
(2, 'AuthorB'),
(3, 'AuthorC'),
(10, 'AuthorD'),
(12, 'AuthorE')
DECLARE
@vartest1 AS VARCHAR(20)
SET @vartest1 = 'AuthorA,AuthorB'
SELECT VALUE AS Names INTO #Temp FROM string_split(@vartest1, ',')
SELECT * FROM #Temp
SELECT * FROM #Authors a
INNER JOIN #TEMP t
ON a.Names=t.Names
SELECT *
FROM #Authors a
INNER JOIN
CASE
WHEN len(@vartest1)>0 #Temp t
ELSE #Authors a
END
ON
CASE
WHEN len(@vartest1)>0 Then #Temp.Names
Else a.Names
END = a.Names
Then I try to create a case join where it either joins to the temporary table or on itself to return all. I've read where people have used unions, but I don't think that'd work for 22 parameters.
caseis an expression, not a statement, and as such can't return anything more than a scalar value. You need to left join both tables with the case in the on condition.