如何将用户定义的类型作为varchar2返回?

时间:2016-11-16 14:35:21

标签: sql oracle oracle11g user-defined-types

让我们考虑一个用户定义类型的表。

create or replace type reftype is object (id number, name varchar2(40), details varchar2(1000));
create table testref(c1 reftype);
insert into testref values (REFTYPE(4, 'asd', 'aaa'));
insert into testref values (REFTYPE(3, 'asf', 'baa'));
insert into testref values (REFTYPE(2, 'asg', 'aba'));
insert into testref values (REFTYPE(1, 'ash', 'aab'));
/
select * from testref;

选择返回包含用户类型对象的列。当我在SQL *中执行它时,我会看到:

SQL> select * from testref
REFTYPE(4, 'asd', 'aaa')
REFTYPE(3, 'asf', 'baa')
REFTYPE(2, 'asg', 'aba')
REFTYPE(1, 'ash', 'aab')

如何编写查询以将此类输出作为文本返回(让我们说varchar2)。

SQL> select substr(c1,1,4) from testref;
select substr(c1,1,4) from testref
              *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected CHAR got KACPER.REFTYPE

同样的:

select substr(cast(c1 as varchar2(1000)),1,4) from testref;

我想将表示用户定义类型的字符串作为文本发送到应用程序而不是UDT。你能告诉我如何写一个返回varchar2表示的查询,就像我在SQL * PLUS中看到的一样吗?

修改

我的真实案例是:

create or replace type reftypetab as table of reftype;

和查询:

select cast(collect(c1) as reftypetab) from testref;

我希望将输出作为varchar2:'KACPER.REFTYPETAB(KACPER.REFTYPE(4,'asd','aaa'),KACPER.REFTYPE(3,'asf','baa'),KACPER.REFTYPE(2,'asg','aba'),KACPER.REFTYPE(1,'ash','aab'))'或XML。但是在打电话时:

select xmltype(cast(collect(c1) as reftypetab)) from testref;

我得到了:

ORA-06553: PLS-306: wrong number or types of arguments in call to 'XMLTYPE'

您有什么建议我如何获取表格类型的XML或文本表示?

2 个答案:

答案 0 :(得分:5)

你可以使用这个:

SELECT T.c1.ID, T.c1.NAME, T.c1.details
FROM TESTREF T;

如果您想要一体化(XML字符串),您也可以使用

SELECT XMLTYPE(c1)
FROM TESTREF;

另一种方式是这个:

CREATE OR REPLACE TYPE reftype IS OBJECT (ID NUMBER, NAME VARCHAR2(40), details VARCHAR2(1000),
    MEMBER FUNCTION TO_VARCHAR2 RETURN VARCHAR2);

CREATE OR REPLACE TYPE BODY reftype IS 

MEMBER FUNCTION TO_VARCHAR2 RETURN VARCHAR2 IS
BEGIN
    RETURN SELF.ID||','||SELF.NAME||','||SELF.details;
END TO_VARCHAR2;

END;
/


SELECT t.c1.TO_VARCHAR2()
FROM TESTREF t;

答案 1 :(得分:2)

尝试这样的事情:

select t.c1.id||','||t.c1.name||','||t.c1.details text
from testref t;

TEXT
----------------
4,asd,aaa
3,asf,baa
2,asg,aba
1,ash,aab

NB由于我从未理解的原因,明确的表别名是强制性的 - 即以下工作:

-- No alias:
select c1.id||','||c1.name||','||c1.details text
from testref;

-- Implicit use of table name as alias:
select testref.c1.id||','||testref.c1.name||','||testref.c1.details text
from testref;