Without using dynamic SQL, the best approach is:
IF condition
BEGIN
SELECT x.*
FROM MyTable x
WHERE x.col1 = @val1
AND x.col2 = @val2
END
ELSE IF condition
BEGIN
SELECT y.*
FROM MyTable y
WHERE y.col1 = @val1
AND y.col3 = @val3
END
ELSE
BEGIN
SELECT z.*
FROM MyTable z
WHERE z.col1 = @val1
AND z.col4 = @val4
END
OR
s and/or conditional logic will impact both performance, readability, and maintainability.
The benefit to the dynamic SQL approach is that it would perform as well as the non-dynamic counterpart I first posted, but only be one SQL statement so there's less concern of someone tweaking one of the conditions to return different values/data/columns:
DECLARE @SQL NVARCHAR(4000)
SET @SQL = 'SELECT t.*
FROM MYTABLE t
WHERE t.col1 = @param1 '
SET @SQL = @SQL + CASE
WHEN condition1 THEN ' AND x.col2 = @param2 '
WHEN condition2 THEN ' AND x.col3 = @param3 '
ELSE ' AND x.col4 = @param4 '
END
BEGIN
EXEC SP_EXECUTESQL @SQL
'param1 [data type], param2 [data type], param3 [data type], param4 [data type]',
@param1, @param2, @param3, @param4
END
For more info on Dynamic SQL in SQL Server, I recommend reading this article. There is a risk of SQL injection if not using parameterized queries, and be aware that using EXEC
does not cache the query plan while using EXEC SP_EXECUTESQL
does cache the query plan.