I have a table of course :
I want to fetch data from searching based on columns Country, university, level, interest and substream.
Query which I've tried but not getting better result.
select *
from edu_college_desc
where (country = @country and
university = @university and
leveln = @level and
interest = @interest and
substream=@substream)
or (country = @country or
university = @university or
leveln = @level or
interest = @interest or
substream = @substream)
What I want to do is: if select only country then the data should come based on only country or if I select only stream then data fetched based from stream only if I select both or more then data fetch should be based on those columns.
How can I get perfect results?
Try this method,
select * from edu_college_desc
where country = ISNULL(@country ,country)
and university = ISNULL(@university ,university)
and leveln = ISNULL(@level ,leveln)
and interest = ISNULL(@interest ,interest
and substream = ISNULL(@substream,substream)
In this you can pass the value NULL
to any of the parameters if it is not selected.(ie If you have set value only for @university and others are NULL
, then result will be university = @university
)
For each category, check if the parameter is null (not given) or the same as specified:
select *
from edu_college_desc
where (@country is null or country = @country)
and (@university is null or university = @university)
and etc...
And, of course, you can also use MS SQL Server's ISNULL
, just as in Abdul Rasheed answer. Convenient but less portable.
您的查询应类似于:
SELECT * FROM edu_college_desc WHERE (@country IS NULL OR country = @country) AND (@university IS NULL OR university = @university) AND (@level IS NULL OR level = @level ) AND (@interest IS NULL OR interest = @interest) AND (@substream IS NULL OR substream= @substream)
此代码肯定会为您提供帮助。
SELECT * FROM edu_college_desc WHERE (country = @country or isnull(@country,0)= 0) AND (university = @university or isnull(@university,0)= 0) AND (leveln = @leveln or isnull(@leveln,0)= 0) AND (interest = @interest or isnull(@interest,0)= 0) AND (substream=@substream or isnull(@substream,0)= 0)
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.