Union causing an ORA-01790: expression must have s

2019-06-05 01:53发布

问题:

With the following query as an example:

  select p.product_id, p.product_name, 
     product_type as product_type,
      from products
    group by p.product_id, p.product_name
  union
    select p.product_id, p.product_name, 
     cast(collect(coalesce(product_type, decode(product_description,null,'DESCR' || '-' product_description) as my_type) as product_type,
    from products
    group by p.product_id, p.product_name

The select statement in the first query returns product_type as a varchar and on the second query product_type is of type my_type. This is causing and ORA-01790: expression must have same datatype as corresponding expression because the data types are not the same.

Is it possible to cast product_type on the first query to be of type my_type?

I tried changing the first query as shown below but with no luck.

select p.product_id, p.product_name, 
     cast(product_type as my_type) as product_type,
     decode(product_source_location, null, 'NO_SOURCE', product_source_location)
    from products
    group by p.product_id, p.product_name

Edit

my_type is defined as 'TYPE "my_type" AS TABLE OF varchar2(4000)'

回答1:

I think you cannot do such casting in SQL. But in PL/SQL you can:

CREATE OR REPLACE TYPE STRARRAY AS TABLE OF VARCHAR2 (255)
/

DECLARE
  tab STRARRAY;
  cnt NUMBER:= 0;
BEGIN
 SELECT COUNT(*)
  INTO cnt
   FROM TABLE(CAST(tab AS strarray));
  dbms_output.put_line(cnt);
END;
/

I think I was wrong in my assumptions above. I did not delete that as it is still valid example. Below example casting existing table column (emp table) with COLLECT as type of table_type:

CREATE OR REPLACE TYPE varchar2_ntt AS TABLE OF VARCHAR2(4000);
/

SELECT deptno
    , CAST(COLLECT(ename) AS varchar2_ntt) AS emps
  FROM   scott.emp
GROUP  BY deptno
/

-- This is dumb but works:

SELECT deptno
     , CAST(COLLECT(ename) AS varchar2_ntt) AS emps
  FROM   scott.emp
 GROUP  BY deptno
 UNION ALL
 SELECT deptno
     , CAST(COLLECT(ename) AS varchar2_ntt) AS emps
   FROM   scott.emp
  GROUP  BY deptno
 /