Question

I have a query that has

... WHERE PRT_STATUS='ONT' ...

The prt_status field is defined as CHAR(5) though. So it's always padded with spaces. The query matches nothing as the result. To make this query work I have to do

... WHERE rtrim(PRT_STATUS)='ONT'

which does work.

That's annoying.

At the same time, a couple of pure-java DBMS clients (Oracle SQLDeveloper and AquaStudio) I have do NOT have a problem with the first query, they return the correct result. TOAD has no problem either.

I presume they simply put the connection into some compatibility mode (e.g. ANSI), so the Oracle knows that CHAR(5) expected to be compared with no respect to trailing characters.

How can I do it with Connection objects I get in my application?

UPDATE I cannot change the database schema.

SOLUTION It was indeed the way Oracle compares fields with passed in parameters.

When bind is done, the string is passed via PreparedStatement.setString(), which sets type to VARCHAR, and thus Oracle uses unpadded comparision -- and fails.

I tried to use setObject(n,str,Types.CHAR). Fails. Decompilation shows that Oracle ignores CHAR and passes it in as a VARCHAR again.

The variant that finally works is

setObject(n,str,OracleTypes.FIXED_CHAR);

It makes the code not portable though.

The UI clients succeed for a different reason -- they use character literals, not binding. When I type PRT_STATUS='ONT', 'ONT' is a literal, and as such compared using padded way.

Was it helpful?

Solution

Note that Oracle compares CHAR values using blank-padded comparison semantics.

From Datatype Comparison Rules,

Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, text literals, or values returned by the USER function.

In your example, is 'ONT' passed as a bind parameter, or is it built into the query textually, as you illustrated? If a bind parameter, then make sure that it is bound as type CHAR. Otherwise, verify the client library version used, as really old versions of Oracle (e.g. v6) will have different comparison semantics for CHAR.

OTHER TIPS

If you cannot change your database table, you can modify your query.

Some alternatives for RTRIM:

.. WHERE PRT_STATUS like 'ONT%' ...

.. WHERE PRT_STATUS = 'ONT ' ... -- 2 white spaces behind T

.. WHERE PRT_STATUS = rpad('ONT',5,' ') ...

I would change CHAR(5) column into varchar2(5) in db.

You can use cast to char operation in your query:

... WHERE PRT_STATUS=cast('ONT' as char(5))

Or in more generic JDBC way:

... WHERE PRT_STATUS=cast(? as char(5))

And then in your JDBC code do use statement.setString(1, "ONT");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top