Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a table test with name varchar(20),id int & gender char(1) columns.I want to write the condition using gender.

If gender=0 then show all gender details
gender=1 then male
gender=2 then female

This query is not showing any detail..can any one give suggestion.

Thank you.

What I have tried:

SQL
select name,gender from test where case when @Gender=0 then 1 else a.Gender end =case when @Gender=0 then 1 else @Gender end
Posted
Updated 27-Feb-17 1:37am
v3

Don't use CASE in a WHILE, use AND and OR instead. Assuming a.Gender is also 1 for male and 2 for female, try:
SQL
... WHERE @Gender = 0 OR @GENDER = a.Gender
 
Share this answer
 
This is simple. Try following query. (I don't really understand what you want to display when the gender = 0. So in my query I display blank when gender is 0)

SQL
select name,
	case when gender = '0' then ''
		when gender = '1' then 'male'
		when gender = '2' then 'female' end as gender
from test
 
Share this answer
 
Comments
CHill60 27-Feb-17 10:40am    
When gender = 0 the OP wants to include both male and female records, if gender = 1 then they want to display only male records and if gender = 2 only female records. Your solution does not do this - it only converts the number to a varchar.
declare @Gender int

select name,gender, case when @Gender = 0
then (select * from test
where Gender in ('Male','Female') )
when @Gender = 1 then (select * from test
where Gender = 'Male')
when @Gender = 2 then (select * from test
where Gender = 'Female')
end
from test
 
Share this answer
 
Comments
CHill60 27-Feb-17 10:44am    
This is syntactically incorrect - it won't even run without producing errors
Msg 116, Level 16, State 1, Line 6
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 116, Level 16, State 1, Line 8
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 116, Level 16, State 1, Line 10
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900