2

I'm trying to create an Oracle query that will use a parameter based on the CommandName of a button.

So here's my query

SELECT id 
FROM table 
WHERE dateTime IS (CASE WHEN :CommandName = 'FIRST' THEN NULL ELSE NOT NULL END)

So I'm passing the parameter but it's not working - I'm just getting a Missing NULL keyword error

I basically don't want to have to write two separate queries based on the parameter that is input

Not even sure if this is possible or if this is the right way of doing it?

Any ideas?

3 Answers 3

4

You may want to read up on the CASE statement a bit more.

I believe you want the following code:

SELECT
    id 
FROM 
    table 
WHERE 
    (
        (dateTime IS NULL AND :CommandName = 'FIRST')
        OR
        (dateTime IS NOT NULL AND NVL(:CommandName, '') <> 'FIRST')
    )
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the info - Is it better to use != or <> different places say different things
<> is ANSI standard while != is not compatible in all database systems (though in this case it is in the vast majority).
Ah good spot - updated the SQL to have an NVL when checking if it does not equal FIRST
1

Without using dynamic SQL to return the string 'NULL' or 'NOT NULL' you could use two NVL() functions:

select id
from table
where NVL(dateTime,'FIRST') = NVL(:param,dateTime);

However, if dateTime is indexed (and Oracle can index NULLs), ths NVL() function will disable the index.

3 Comments

Ah interesting way though based on the assumption :param is FIRST or NULL
Oracle will evaluate "NULL = NULL" to NULL, so it will not return anything in that case.
@jva True, but the first NVL() on the left side of the operator provides an alternative value when dateTime is null ('FIRST'), so the first expression is never null. IF :param is null, the dateTime column will be used for all rows, and any rows where datetime is in fact null will be discarded since 'FIRST' = NULL evaluates to false. That said, I'm digging @John D's solution with the OR operator, although I'd wrap that mutually exclusive pair of conditions in parenthesis so other predicates will be applied as expected.
0

I think that

SELECT id 
FROM table 
WHERE (dateTime IS NULL AND :CommandName='FIRST') OR (dateTime IS NOT NULL AND :CommandName <> 'FIRST')

should do what you need.

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.