views:

21

answers:

1

Hi Guys,

DECLARE @cityID bigint;
set @cityID = NULL
--set @cityID = 3

SELECT ID,
        Name,
        CityID,
        IsProvince
FROM TABLE t
    WHERE ISNULL(t.CityID, -1) = ISNULL(@cityID, -1)

whenever the @cityID is NULL the t.CityID is also NULL for that record.

Only one record can ever be true for IsProvince

Is there a way to check without doing the if-else clause if I want to do the following:

1) If the @cityID is NULL, then get the record whose IsProvince is 1

2) If the @cityID is NOT NULL then get the record whose CityID = @cityID

Thanks,

Voodoo

+1  A: 

You can do this in the WHERE:

DECLARE @cityID bigint;
set @cityID = NULL
--set @cityID = 3

SELECT ID,
        Name,
        CityID,
        IsProvince
FROM TABLE t
    WHERE (@cityID IS NULL AND t.CityID IS NULL AND IsProvince = 1)
          OR (t.CityID = @cityID)

This should work since anything = NULL always returns false. The first clause should solve your #1, and the second solves #2. I'm not sure if you really need the t.CityID IS NULL clause though, since your criteria for #1 doesn't mention it.

Does this make sense?

davisoa
It makes sense, thanks.
VoodooChild
I was worried I didn't completely understand the need, hence asking if it made sense...
davisoa
:) no, you got it. It was just one of these times where your brain hits a brick wall and you start to post your questions instead of thinking about for few minutes....
VoodooChild