There's no need for dynamic SQL here at all; in fact your use of it here is dangerous. You are leaving yourself wide open to SQL injection attacks. I strongly suggest you research the dangers of such a fatal vulnerability. SQLK Injection is a problem that has existed for decades and there is no excuse to writing such code any more; ignorance is not an excuse when so many companies have been named and shamed over the last 15 years for such badly written code resulting in huge numbers of data breaches.
Anyway, onto the answer. One method would be to use a table type parameter. I define a table
variable here, but if this is a call from an application you'll need to look into creating and using a TVP:
SELECT ED.Name,
ED.Age,
ED.Phone,
EA.Address
FROM dbo.EmployeeDetails ED
JOIN dbo.EmployeeAddress EA ON EA.EmpId = ED.EmpID
WHERE ED.Name LIKE '%' + @Name + '%'
AND (EA.Status IN (SELECT Status FROM @Statuses)
OR NOT EXISTS (SELECT 1 FROM @Statuses)
ORDER BY ED.CreatedDate DESC
OFFSET @PageNum * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY
OPTION (RECOMPILE);
Alternertively, if you are passing a delimited string for your list (which it seem you are) you could use a string splitter and split the value. This assumes you are using a fully supported version of SQL Server (if not, look into an inline user defined table value string splitter) and the value is comma (,
) delimited.
SELECT ED.Name,
ED.Age,
ED.Phone,
EA.Address
FROM dbo.EmployeeDetails ED
JOIN dbo.EmployeeAddress EA ON EA.EmpId = ED.EmpID
WHERE ED.Name LIKE '%' + @Name + '%'
AND (EA.Status IN (SELECT SS.[value] FROM STRING_SPLIT(@Status,',') SS)
OR @Status IS NULL)
ORDER BY ED.CreatedDate DESC
OFFSET @PageNum * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY
OPTION (RECOMPILE);