I’m working with a Stored Procedure in SQL Server 2005. Is it possible to use a join if only the parameter is not null ? Below is an example of the query :
ALTER PROCEDURE [dbo].[SPSample]
@gender varchar(20) = null
@username varchar(20) = null
AS
SELECT
per.firstName,
per.lastName,
per.gender
FROM person per
INNER JOIN account ac on ac.idPerson = per.idPerson
WHERE (
gender = @gender
AND (@username is null or (@username is not null and @username = acc.username))
How to make the INNER JOIN only works if the @username is not null ? What is the best approach to get the expected result ?
although not the cleanest, but it works