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.
Author |
Topic |
kpgraci
Yak Posting Veteran
68 Posts |
Posted - 2012-02-02 : 13:17:15
|
I have a table like this:Table: Plans--------------PlanName varchar(50)LOB integerFYI: LOB stands for 'Line of Business' and indicates the kind of insurance policy LOB can be 1,2,3...for a specific LOB or -1 for 'all others'I want to query this table and return all LOBs that match a givien LOB, and if none match, then return all LOBs that are equal to -1So if the table were as follows:Planname LOB--------------Plan1 1Plan2 1Plan3 2Plan4 3Plan5 -1Plan6 -1then the query for LOB=1 should returnPlanname LOB--------------Plan1 1Plan2 1and the query for LOB=7 should return Planname LOB--------------Plan5 -1Plan6 -1also, if LOB is not found and there are no LOB -1's defined, no records should be returned.So my pseduo query is:IF COUNT(SELECT * FROM Plans WHERE LOB=@LOB) = 0 THEN (SELECT * FROM Plans WHERE LOB=-1) ELSE (SELECT * FROM Plans WHERE LOB=@LOB)Is there a way to do this in a single query?kpg |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-02-02 : 13:29:50
|
quote: Originally posted by kpgraci I have a table like this:Table: Plans--------------PlanName varchar(50)LOB integerFYI: LOB stands for 'Line of Business' and indicates the kind of insurance policy LOB can be 1,2,3...for a specific LOB or -1 for 'all others'I want to query this table and return all LOBs that match a givien LOB, and if none match, then return all LOBs that are equal to -1So if the table were as follows:Planname LOB--------------Plan1 1Plan2 1Plan3 2Plan4 3Plan5 -1Plan6 -1then the query for LOB=1 should returnPlanname LOB--------------Plan1 1Plan2 1and the query for LOB=7 should return Planname LOB--------------Plan5 -1Plan6 -1also, if LOB is not found and there are no LOB -1's defined, no records should be returned.So my pseduo query is:IF COUNT(SELECT * FROM Plans WHERE LOB=@LOB) = 0 THEN (SELECT * FROM Plans WHERE LOB=-1) ELSE (SELECT * FROM Plans WHERE LOB=@LOB)Is there a way to do this in a single query?kpg
SELECT *FROM tableWHERE LOB = @YourValueUNION ALLSELECT *FROM tableWHERE LOB = -1AND NOT EXISTS (SELECT 1 FROM tableWHERE LOB = @YourValue) ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
kpgraci
Yak Posting Veteran
68 Posts |
Posted - 2012-02-02 : 16:09:15
|
Very clever :) Thanks!kpg |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-02-02 : 18:21:26
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|