I am something of a beginner to SQL and I am trying to run the following SP.
DECLARE @stringStatus varchar(100)
--Check for status value
IF @Status is NULL
BEGIN
set @stringStatus = ''
END
ELSE
BEGIN
set @stringStatus = ' and ps.Status = ' + CAST(@Status as varchar)
END
select * from Projects p
join projectstatus ps on p.pid = ps.pid
where ps.Category = isnull(@Category, p.Category) + @stringStatus
The aim of the above is to get all rows if @Status is NULL, and to filter the rows, if a parameter has been assigned to @Status.
@Category (varchar) and @Status (int) are IN paramateres
This works fine when @Status is NULL, i.e, I get all the records. But if I pass a parameter, say, @Status = 2, the execution returns no rows, even though there are a few records available.
First of all, how do I get my desired results? Secondly, is there a better way to do this without an if condition block?