I need to write a SQL query that retrieves records based on supplied RoleId.
e.g.
- If RoleId = 1 THEN _t1.CreatedBy = @LoginUserId.
For other RoleId, I want all records from table without any condition on CreatedBy column.
I am providing sample query as per my requirement.
SELECT _t1.*
FROM [dbo].[TblPassDetail] _t1 WITH (NOLOCK)
INNER JOIN [dbo].[TblVisitor] _t2 WITH (NOLOCK) ON _t1.VisitorId = _t2.SrNo
WHERE _t1.LocationId = @LocationId
AND _t1.CreatedBy = (CASE WHEN @RoleId = 1 THEN @LoginUserId ELSE 0 END)
Issue is that if supplied @RoleId is 1, I am getting all records for that LoginUserId, but if @RoleId is anything other than 1, then I am not getting any records as SQL checking records for _t1.CreatedBy = 0 which doesn't exist in the table.
Any suggestion on how to rewrite my query?