0

This is my query

select id,name,address from emp_details where gender = ?

Input : Female , Male

In this usually I need to fetch only Female data or only Male data But some times I need to fetch both Female and Male data using the same query..

Is it possible? If so, how?

RNJ
  • 15,272
  • 18
  • 86
  • 131
vino
  • 119
  • 1
  • 8
  • You want to use something like the in clause which is explained [here](http://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives) – RNJ Sep 17 '12 at 08:53
  • An in clause wouldn't help. The number of parameters would be 1 in the first case, and 2 in the second case. So the SQL query would be different. – JB Nizet Sep 17 '12 at 08:54
  • how do you know ? when you need both data? – subodh Sep 17 '12 at 09:02

5 Answers5

2

just invert the query:

select id,name,address from emp_details where gender <> ?

and specify "male" for getting females, "female" for getting males, and "whatever" for getting both.

jdevelop
  • 12,176
  • 10
  • 56
  • 112
1

Using the same query, no, it's not possible. Use a query without any where clause to do that:

select id,name,address from emp_details
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Use the in-clause

where gender in ?

and as parameter a array of string

new String[]{"m","f"}
Grim
  • 1,938
  • 10
  • 56
  • 123
  • Works for me, what a db do you use? – Grim Sep 17 '12 at 09:55
  • Oracle, for instance. But I wonder how it can work on yours. See http://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives and http://stackoverflow.com/questions/303218/how-do-i-bind-an-arraylist-to-a-preparedstatement-in-oracle for example. See also http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html which has been created by Spring to allow named parameters AND list expansion into multiple parameters – JB Nizet Sep 17 '12 at 10:25
1
SELECT id , name , address
FROM emp_details 
WHERE gender IN (?,?);

Male of Female only => set for both ? the same value

PreparedStatement IN clause alternatives?

Community
  • 1
  • 1
Err
  • 291
  • 2
  • 13
1
    String gender="Female ";

    String sql = "select id,name,address from emp_details";

    if(gender!=null && !"".equals(gender))

     {      
        sql+=" where gender = ?";

     }
subodh
  • 6,136
  • 12
  • 51
  • 73