4

I have an Mysql query

SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = ?
    AND DESIGNATION = ?
    AND DISTRICT = ?
    AND CIRCLE = ?

And quite possible any 1 or 2 or 3 of the parameter (?) can be empty or null.

so what should I do so that the empty parameters are totally Ignore in the where clause and only search for the non-empty parameter in the table.

How can I achieve this

Please help.. The query must be compatible mysql. Thanks

1 Answer 1

4

You could add the input parameters twice and make the query like this:

SELECT *
FROM EMPLOYEE
WHERE (DEPARTMENT = ? OR ? IS NULL)
    AND (DESIGNATION = ? OR ? IS NULL)
    AND (DISTRICT = ? OR ? IS NULL)
    AND (CIRCLE = ? OR ? IS NULL)

So on the first and second '?' you bind the same value.

Alternatively (and arguably better), you can build the SQL dynamically, and leave out certain parts of the where clause if it doesn't apply. You can concat the strings to get the basic SQL and still use bind parameters.

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.