Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Where for a select

Author  Topic 

Mogman
Starting Member

2 Posts

Posted - 2011-10-11 : 11:55:49
So I'm trying to get a where statement in a select to work instead of using a large amount of if statements... I ALMOST have my head wrapped around it but I just can't get it that extra bit to make it all work.

What I have...
Declare @ProvinceID int, @CityID int, @EventTypeID int

Set @ProvinceID = 7
Set @CityID = 0
Set @EventTypeID = 38

select * from Events
where (
(EventTypeID=@EventTypeID or ProvinceID=@ProvinceID or CityID=@CityID)
-- This covers just 1 of the variables being filled but also causes issues if 2 or 3 are filled
or
(
(EventTypeID=@EventTypeID and CityID=@CityID) or (EventTypeID=@EventTypeID and ProvinceID=@ProvinceID)
-- Covers if 2 are filled but breaks if all 3 are filled and won't work anyways as the first part of the where has or but if I add and it won't work with 1 variable
)
or
(
(EventTypeID=@EventTypeID and CityID=@CityID) and (EventTypeID=@EventTypeID and ProvinceID=@ProvinceID)
-- Covers all 3 being filled.
)
)


Since the 3 variables can be separate or intermixed it would be a tonne of ugly looking ifs or just a bit of brain power and a somewhat ugly where.

Anyone care to help me get over this hump?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-10-11 : 12:34:42
[code]
Declare @ProvinceID int, @CityID int, @EventTypeID int

Set @ProvinceID = 7
Set @CityID = 0
Set @EventTypeID = 38

select * from Events
where (EventTypeID=@EventTypeID or @EventTypeID is null)
and (ProvinceID=@ProvinceID or @ProvinceID is null)
and (CityID=@CityID or @CityID is null)
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Mogman
Starting Member

2 Posts

Posted - 2011-10-11 : 12:58:01
Did a quick switch to test for 0 instead of null and worked like a charm.

Thank you!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-10-11 : 13:11:13
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -