简体   繁体   中英

SQL fallback or c# datatable

say I have ten cars

columns for color, engine_size, type, make... etc there is 50 columns

I want to select for example:

SELECT * FROM CARS WHERE COLOR = 'red' AND ENGINE_SIZE = 'V8' AND TYPE = 'coupe' and MAKE = 'Ford' etc for all 50 columns...

but... and this where I'm stuck for the last week... I do not want the whole SELECT statement to come back empty when a condition is not met... I want it to fallback to whatever it could get...

for example if it only finds cars that are red and are Ford coupes but none are V8s then instead of coming back empty I want it to return the records that are red and coupes and Ford... and I have to do that for all 50 columns...

After trying and googling for a week I realise that SQL has no way to alter itself on the fly... you make a SELECT statement then it goes off and runs it... it has no way to go okay that part of the statement returns empty so I'll fall back to the bit that did work..

So now I'm thinking I need to do it with c# and write some ghastly code that keeps iterating through a datatable over and over gradually reducing it until it leaves what it could find.

This does not seem elegant and I'm wondering if there is a better way? I have not posted any of my sample code because nothing I've tried (ISNULL, IF EXISTS, etc) does anything close to what I want to achieve. I just get back nothing or everything.

To simplify what I'm saying with psuedocode:

If result != empty

select * where Color = 'red' and Type = 'coupe' and Make = 'Ford' etc (for 50 conditions)

else

select * where Color = 'red' and Type = 'coupe' and Make = 'Ford' etc (for 49 conditions)

... etc

but even this will fail because I would have to test for every possible combination of those 50 conditions... not just 50 one after another

This is my first time posting here so my apologies if I haven't explained myself very well.

You can use order by instead of where :

select top 1 c.*
from cars c
order by ((case when Color = 'red' then 1 else 0 end) + 
          (case when Type = 'coupe' then 1 else 0 end) + 
          (case when Make = 'Ford' then 1 else 0 end) + 
          . . .
         ) desc;

You can, of course, adjust the "1"s to give weightings to the different features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM