Search code examples
sqloracle-databaseunpivot

Cannot search in all columns of differing types


This looks like an old question but it's actually not. I couldn't find an answer on SO or elsewhere.

I have this table:

n (number) | s (varchar2)
-------------------------
200        | some string
201        | some other string

I can cast the number n to a string and select it without problems like so:

SELECT n FROM t;
SELECT TO_CHAR(n) FROM t;

But I need to search in all columns for a string value. What I've tried (and it works generally, meaning the DB is an 11g) is UNPIVOT:

SELECT * FROM t UNPIVOT (anywhere FOR col IN (...));

However, what does NOT work is mixing data types (numbers and character-based types such as varchar2). What I get is:

ORA-01790: expression must have same datatype as corresponding expression

That's ok, I understand this and the solution is obvious. Cast numbers to characters. But that doesn't work either. For the immediate solution:

SELECT * FROM t UNPIVOT (anywhere FOR col IN (s, TO_CHAR(n)));
                                                        ^

I get this unexpected error:

ORA-00917: missing comma

The problem here is that TO_CHAR is not interpreted as a function at all, it is thought to be a column name like s or n.

So, how can I use UNPIVOT with mixed data types or how can I cast all columns to varchar2 or how else can I solve this problem?


Solution

  • Try using:

    SELECT * 
      FROM (SELECT to_char(n) as n, s FROM t) 
    UNPIVOT (anywhere FOR col IN (...));