0

I am trying to figure out this stored procedure.

ALTER procedure [dbo].[GetTotals]

@Service nvarchar(50),
@Country nvarchar(50)  = NULL,
@Region nvarchar(50) = NULL

as 

SELECT
  CASE @Service
    WHEN 'Army' THEN Sum(Army)
    WHEN 'Navy' THEN Sum(Navy)
    When 'Marine_Corps' then Sum(Marine_Corps)
    When 'Air_Force' then Sum(Air_Force)
    ELSE NULL
  END      as "ServiceTotal"

FROM
  All_Records

WHERE Country = CASE WHEN @Country IS NOT NULL THEN @Country ELSE Country END
  AND Region = CASE WHEN @Region IS NOT NULL THEN @Region ELSE Region END

What I want is if @Country is not null, then return records where Country = @Country, Else returns all countries. I want the same behavior for Region.

I have tried Else Is Not Null, and Else !=Null, and Else <> Null

But nothing is working.

Edit:

I figured it out. I just wasn't calling the procedure correctly. It is working. I have to call the procedure, named GetTotals like this:

  • GetTotals Navy, Null, Europe This would return total Navy for all of europe.
  • GetTotals Navy, Albania, Null This would return totals for Navy in Albania

2 Answers 2

3

This is often done like this:

WHERE COALESCE(@Country,Country) = Country AND COALESCE(@Region,Region) = Region
Sign up to request clarification or add additional context in comments.

1 Comment

Also in SQL Server ISNULL() is an alternative ;).
1
WHERE (Country = @Country OR @Country IS NULL) AND (Region = @Region OR @Region IS NULL)

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.