来自Varray ORACLE SQL的SELECT值

时间:2018-01-04 12:21:25

标签: sql oracle varray

我使用的是apex.oracle,我得到的错误是[unsupported data type]。 解释:我有一个名为Playlist的表,我想将一组歌曲存储到Songs字段中。出于这个原因,我已经定义了一个名为PlaylistSongs varray chars的{​​{1}}类型。插入有效,但是当我执行SELECT时,我得到[unsupported data type]而不是带有值的数组。

这是代码

CREATE OR REPLACE TYPE PlaylistSongs AS VARRAY(4) OF CHAR(16);

CREATE TABLE PLAYLIST (
    IDPlaylist              NUMBER(4) NOT NULL,
    PlaylistName            CHAR(64),
    PlaylistAuthor          NUMBER(2),
    PlaylistDuration        NUMBER,
    ActivePlaylist          NUMBER(1),
    Songs                   PlaylistSongs,

    CONSTRAINT PLAYLIST_PRIMARY_KEY PRIMARY KEY (IDPlaylist),
    CONSTRAINT PLAYLIST_FOREIGN_KEY FOREIGN KEY (PlaylistAuthor) REFERENCES DJ (IDDJ)
);

INSERT INTO PLAYLIST VALUES (1, 'Rap', 1, 153, 1, 1, PlaylistSongs('River', 'Lose Yourself', 'Till I Collapse', 'Walk On Water')); 

经过一番研究后,我找到了TABLE运营商。

SELECT *
FROM PLAYLIST p, TABLE(p.Songs) ps

这样可行但不是将数组显示为常规数组,而是显示新行上的每个条目。

enter image description here

我需要它看起来像['River', 'Lose Yourself', 'Till I Collapse', 'Walk On Water']。可以吗?

1 个答案:

答案 0 :(得分:2)

是 - 请参阅listagg()聚合函数(附带group by子句):

select idplaylist
     , playlistname
     , playlistauthor
     , playlistduration
     , activeplaylist
     , listagg(rtrim(ps.column_value), ', ') within group (order by ps.column_value) as songs
from   playlist p
       cross join table(p.songs) ps
group by
       idplaylist
     , playlistname
     , playlistauthor
     , playlistduration
     , activeplaylist;

另外,use varchar2 for strings, not char只是应用了你不需要的空白填充(实际上,没有人需要它 - char仅用于可移植性和ANSI完整性,并不适用于新开发。使用{{ 1}}数组你不需要varchar2