1

我有一个类型声明为

TYPE "TABLE_TYPE" AS TABLE OF varchar2(4000)

如何转换我在查询中选择的列以返回该类型。

例如

Select cast(to_char(sysdate) as TABLE_TYPE) from dual

返回ORA-00932: inconsistent datatypes: expected - got CHAR错误。有没有办法将 varchar2 的列转换为用户定义的类型?

4

4 回答 4

3

使用cast + multiset

select cast(multiset(
    select to_char(sysdate-level, 'YYYYMMDD')
    from dual
    connect by level <= 10
) as t_vchar_tab)
from dual;
于 2013-02-14T20:21:47.800 回答
3

如果你真的想返回一个包含单个元素的集合,你只需要调用类型的构造函数

SQL> create type table_type as table of varchar2(100);
  2  /

Type created.

SQL> select table_type( to_char( sysdate ))
  2    from dual;

TABLE_TYPE(TO_CHAR(SYSDATE))
-----------------------------------------------------------------------------
TABLE_TYPE('14-FEB-13')

但是,通常,当您创建集合时,其目的是通过运行返回多行的查询来使用多个元素填充它。为此,你会想做类似的事情

DECLARE
  l_strs table_type;
BEGIN
  SELECT ename
    BULK COLLECT INTO l_strs
    FROM emp;
  <<l_strs now contains 1 element for each row in the EMP table>>
END;
于 2013-02-14T18:49:05.970 回答
2

导致 ORA-01790 的联合:表达式必须具有与相应表达式相同的数据类型

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
/
于 2013-02-14T19:34:15.487 回答
1
select table_type(to_char(sysdate)) from dual;
于 2013-02-14T18:47:28.507 回答