0

I have a query that is:

SELECT  DISTINCT DepotIo.Depot2Guid AS Depot1Guid, Depot2.Title, NULL AS Depot2Guid
FROM DepotIo
 JOIN DepotIoDetail ON DepotIo.Guid = DepotIoDetail.DepotIoGuid
 JOIN dbo.GetUserDepot(@UserGuid) AS Depot2 ON DepotIo.Depot2Guid = Depot2.Guid
 JOIN Item ON Item.Guid = DepotIoDetail.ItemGuid
WHERE DepotIo.Company = @Company AND (DepotIo.Branch = @Branch)

But I want to when @Branch is not null, comes to WHERE condintion part and when it's value is null, relinquish it.. Like this :

WHERE DepotIo.Company = @Company AND (CASE @Branch 
WHEN IS NOT NULL THEN DepotIo.Branch = @Branch)

what's true command ??

1
  • Can DeDepotIo.Branch be null? Commented Sep 4, 2019 at 10:08

3 Answers 3

2

This is usually handled using or:

WHERE DepotIo.Company = @Company AND
      (DepotIo.Branch = @Branch OR @Branch IS NULL)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use CASE WHEN as follows:

(CASE WHEN @Branch IS NOT NULL 
THEN CASE WHEN DepotIo.Branch = @Branch THEN 1 ELSE 0 END
ELSE 1 END = 1)

Cheers!!

Comments

1

If I understand the question, this should do it. If DeDepotIo.Branch is not nullable. This will relinquish rows where @Branch<>DeDepotIo.Branch, but not when @Branch is NULL.

WHERE DepotIo.Company = @Company AND (ISNULL(@Branch, DeDepotIo.Branch) = DeDepotIo.Branch)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.