从嵌套表Oracle DB中删除特定记录

时间:2013-12-06 12:40:19

标签: oracle nested-table

我在从表中删除特定记录时遇到问题(ORACLE DB)。 我有一个带有嵌套表的表。

表结构如下所示:ML - 嵌套表

Name, City, ML(Brand, Model, ID, Year, Price)

我需要做的是删除ID为“L201”的特定记录。

到目前为止我尝试过:

SELECT B.ID FROM TABLE Dock A, Table(A.ML) B;

这可以给我所有的ID。

输出:

ID
____
B201
S196
L201

尝试删除记录时无效:

DELETE FROM Dock
(SELECT B.ID FROM Dock A, Table(A.ML) B) C
WHERE C.ID = 'L201';

获取错误:

  

第2行:SQL命令未正确结束;

DELETE FROM TABLE
(SELECT D.ML FROM Dock D) E
WHERE E.ID = 'L201';

引发错误:

  

单行子查询返回多行

2 个答案:

答案 0 :(得分:0)

在阅读了一些文献后,我想我找到了正确的方法 通过为对象类型定义映射函数,您可以直接比较两个嵌套表 例如:

-- creating the custom object type
create or replace type ml_type as object (
  brand varchar2(100),
  id varchar2(20),
  map member function sort_key return varchar2
);
-- creating the object type body and defining the map-function
create or replace type body ml_type as
    map member function sort_key return varchar2 is
    begin
        return self.brand || '|' || self.id;
    end;
end;
/
-- creating the nested table of custom type
create or replace type ml_tab as table of ml_type;

-- deleting from your table by comparing the nested-table elements
delete from dock where ml = (select ml from dock a, table(a.ml) b where b.id = 'L201');

在此示例中,map-functions只返回brandid的连接版本,但您可以将其定义为您想要/需要的内容。

答案 1 :(得分:0)

也许这一个:

DELETE FROM 
   (SELECT A.Name, A.City, d.Brand, d.Model, d.ID, d.Year, d.Price 
   FROM Dock A, TABLE(ML) d)
WHERE ID = 'L201';

<强>更新: 在我们提高它之前的另一项试验:

DELETE FROM Dock
WHERE ROWID =ANY (SELECT a.ROWID FROM Dock a, TABLE(ML) b WHERE b.ID = 'L201');

更新2 : 如果您更喜欢它更面向对象,那么这个应该也可以。至少我没有得到任何错误。

CREATE OR REPLACE TYPE ML_TYPE AS OBJECT (
  brand VARCHAR2(100),
  ID VARCHAR2(20),
  MODEL VARCHAR2(20), 
  YEAR NUMBER, 
  Price NUMBER,
MAP MEMBER FUNCTION getID RETURN VARCHAR2,
CONSTRUCTOR FUNCTION ML_TYPE(ID IN VARCHAR2) RETURN SELF AS RESULT);


CREATE OR REPLACE TYPE BODY ML_TYPE IS   

CONSTRUCTOR FUNCTION ML_TYPE(ID IN VARCHAR2) RETURN SELF AS RESULT IS
-- Constructor to create dummy ML-Object which contains just an ID,
-- used for comparison
BEGIN
    SELF.ID := ID;
    RETURN;
END ML_TYPE;

MAP MEMBER FUNCTION getID RETURN VARCHAR2 IS
BEGIN
    RETURN SELF.ID;
END getID;
END;
/

CREATE OR REPLACE TYPE ML_TABLE_TYPE IS TABLE OF ML_TYPE;

CREATE TABLE Dock (Name VARCHAR2(20), City  VARCHAR2(20), ML ML_TABLE_TYPE) 
NESTED TABLE ML STORE AS ML_NT;

insert into Dock values ('A', 'NY', ML_TABLE_TYPE(
  ML_TYPE('brand1','L301','Model 2',2013, 1000),
  ML_TYPE('brand2','L101','Model 3',2013, 1000)));

insert into Dock values ('B', 'NY', ML_TABLE_TYPE(
  ML_TYPE('brand3','K301','Model 4',2014, 3000),
  ML_TYPE('brand4','K101','Model 5',2014, 3000)));

insert into Dock values ('A', 'NY', ML_TABLE_TYPE(
  ML_TYPE('brand5','K301','Model 8',2012, 2000),
  ML_TYPE('brand6','L201','Model 9',2012, 2000)));


DELETE FROM Dock WHERE ML_TYPE('L201') MEMBER OF ML;