Add WHERE clauses to SQL dynamically / programmatically

You can do this in sql only, like this:

SELECT * 
FROM tUsers 
WHERE 1 = 1
  AND (@userID IS NULL OR RTRIM(Name) = @userID )
  AND (@password IS NULL OR RTRIM(Password) = @password)
  AND (@field2 IS NULL OR Field2 = @field2)
....

If any parameter passed to the stored procedure with a NULL value then the whole condition will be ignored.

Note that: I added WHERE 1 = 1 in order to make the query work in case no parameter passed to the query and in this case alll the result set will be returned, since 1 = 1 is always true.

Leave a Comment