Filtering Question — Probably easy! | SQL Server Performance Forums

SQL Server Performance Forum – Threads Archive

Filtering Question — Probably easy!

<font face="Tahoma"><br /><font size="2"><br />Hello,<br /><br />I have a question on the best way to do a particular SQL query. This is the basic idea of what I want to do:<br /><br /><pre id="code"><font face="courier" size="2" id="code"><br />DECLARE @Status INT<br />DECLARE @ExcludeStatus INT<br /><br />SET @Status = Null<br />SET @ExcludeStatus = 5<br /><br />SELECT <br /> r.RecordNumber, r.Status <br />FROM <br /> Records r <br />WHERE <br /> ISNULL(r.Status, ”) = COALESCE(@Status, r.Status, ”)<br /> AND ISNULL(r.Status, ”) != COALESCE(@ExcludeStatus, ”, ”)<br /></font id="code"></pre id="code"><br /><br />The above query works, but I would like to avoid using the @ExcludeStatus parameter. Basically, I just want to exclude status 5 by default, unless it’s specifically requested in the @Status parameter. <br /><br />So, I would like to be able to submit null for @Status, and get only status 1, 2, 3 and 4. I would like to be able to specify a status 1-5 and get only that status (including 5).<br /><br />This is probably easy for must of you… I’m not a DBA <img src=’/community/emoticons/emotion-6.gif’ alt=’:(‘ /><br /><br /></font id="size2"><br /></font id="Tahoma">
Hi ya, I’d use an if condition for this… DECLARE @Status INT
DECLARE @ExcludeStatus INT
SET @Status = Null
SET @ExcludeStatus = 5 if @Status is null
SELECT r.RecordNumber,
r.Status
FROM Records r
WHERE r.Status in ( 1, 2, 3, 4 )
else
SELECT r.RecordNumber,
r.Status
FROM Records r
WHERE r.Status = @Status Cheers
Twan
]]>