0

Got this sql (selection between ranks):

//Variables come from outside or other classes etc... 
"SELECT * from users where dept_name= ? AND birth_date >=? AND birth_date <=? AND money >=? AND money <=?;  
//Long preparedStatement code...

Using the next code to pass dept_name to the sql:

System.out.println("Insert department name: ");
Scanner alpha = new Scanner(System.in);
String dept_name= alpha.nextLine();

What happens if I don't insert anything on the scanner and I simply press enter? Like if I want to skip the search by dept_name and I only want to search between birth_date and money ranks?

How can I handle:

pstmt.setString(1, users.getDeptname()); //prepared statement

If it previously received a "enter" as character on the dept_id ?

How can Oracle ignore dept_name =? if no valor is passed in the "?" with prepared statement and use the next fields in the SQL to continue the query?

1 Answer 1

1

You can modify the query to something like

SELECT * FROM users 
WHERE (dept_name = ? OR ? IS NULL) AND .....

Then in the code you setting pstmt.setString(1, dept_name); pstmt.setString(2,dept_name);

However, I'd rather have multiple statements then one that fits all. The problem with any universal approach is performance. Optimizer will not be able to generate good execution plan . For instance, if username is set, range/unique scan of underlying index is definitely preferable over full table scan. Even though Oracle 11 and higher has nice features like bind awareness, I'm not 100% sure it will handle all the cases in optimal way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.