You can write this SQL as:
SELECT e.Date AS Date, u.UserName AS UserName, e.Enter AS Enter, e.Leave AS Leave
FROM Entries e INNER JOIN
Users u
ON e.UserID = u.Id
WHERE u.UserName LIKE @UserName or @UserName is NULL;
(The aliases just make the query easier to write and to read.)
However, there are reasons why this might not be a great idea. Having an or condition can make it harder for SQL Server to use an index. With one variable, it might be all right. With multiple variables, this could have a big impact on performance.
If that is a concern, then write the query in the application as dynamic SQL. Start with a where clause like:
declare @where varchar(8000) = '1=1'
And then build it:
if @UserName is not NULL
begin
set @where = @where + ' and UserName = @UserName';
end;
and continue this for each clause.
( (1=1 and @UserName is null) or ( @UserName is not null and UserName LIKE @UserName) )ANDis used, everything in the parenthesis must be true. If you pass in nothing for UserName, then it will bring back everything as 1=1 and @UserName is null, true statement. If you pass in a username, then the first set of parenthesis are false, so the second set (after theor) are used. UserName is not null, true in this case, and the UserName LIKE is executed against the UserName passed in. However, I think the 1=1 is redundant.