如何在sql(oracle)的嵌套表中添加元素?

时间:2018-12-03 18:58:22

标签: sql oracle11g nested-table object-relational-model

假设我正在使用一个表person,并且person可能有多个姓,因此该属性应存储在嵌套表中(这与存储姓的位置无关),这是一个用于创建last类型的简单sql名称,表人,并在oracle的sql developer(11G XE)中添加示例行:

create type lastn as table of varchar2(10);
CREATE TABLE person
(
ID NUMBER NOT NULL 
, last_name lastn
, CONSTRAINT EXEMPLE_PK PRIMARY KEY 
(
 ID 
)
ENABLE 
)nested table last_name store as ln;
insert into person values(1,ln('dani','bilel'));

我知道如何一次更新所有姓氏,但是我需要保留现有的姓氏并添加其他姓氏,或者删除一个姓氏而不影响其他姓氏。简而言之,我希望我的代码像(我不熟悉PL / SQL):

update person set last_name=last_name+'third last name' where id=1;

我知道它不能那样工作,我应该使用PL / SQL吗?,是否可以通过其他方式使用?

请原谅我的问题,谢谢您的答复。

1 个答案:

答案 0 :(得分:0)

您可以使用表集合运算符插入嵌套表:

insert into table(select last_name from person where id = 1) values ('third');

1 row inserted.

select last_name from person where id = 1;

LAST_NAME                                         
--------------------------------------------------
LASTN('dani', 'bilel', 'third')

您可以用相同的方式删除元素:

delete from table(select last_name from person where id = 1) where column_value = 'bilel';

1 row deleted.

select last_name from person where id = 1;

LAST_NAME                                         
--------------------------------------------------
LASTN('dani', 'third')

,您甚至可以更新它们:

update table(select last_name from person where id = 1)
set column_value = 'second' where column_value = 'third';

1 row updated.

select last_name from person where id = 1;

LAST_NAME                                         
--------------------------------------------------
LASTN('dani', 'second')