Is it possible to build a dynamic where clause in a stored procedure such that if the parameter is empty, you select all item in the table? However, if you do have a parameter, you select items where the condition is true?
1 Answer
Here is the trick... you can create a string query for your select command, and then manipulate it by conditional statement.. see sample below.. hope you can apply the logic on your work.
-- Put a default value `NULL` to your parameter first
CREATE TABLE TableNameHere
(
@ParameterName VARCHAR(MAX) = NULL
)
DECLARE @SQLQuery VARCHAR(MAX)
--Initialize SQL statement first
--It will return true always , therefor it will display all data
SET @SQLQuery = 'SELECT * FROM TableNameHere WHERE 1 = 1'
-- If parameter has a value then do the where condition inside the block
IF @ParameterName IS NOT NULL
BEGIN
SET @SQLQuery = @SQLQuery + ' AND ColumnNameHere = ''' + @ParameterName + ''''
END
EXEC(@SQLQuery)
WHERE (@parameter IS NULL OR col = @parameter)whereclause:where (@id is null or id = @id).