【问题标题】:Stored procedure to Convert Clob field of table into xmltype and split xml values to store in the table将表的 Clob 字段转换为 xmltype 并拆分 xml 值以存储在表中的存储过程
【发布时间】:2021-08-30 03:47:11
【问题描述】:

我有一张带有 Clob 字段的表格

Create table xml_data
(id number,employee_data clob);

Employee_data table xml :
<employees>
<employee id=1>
<properties Name="firstname">Sherlock</properties>
<properties Name="lastname">Holmes</properties>
<properties Name="age">30</properties>
<properties Name="department" >investigation </properties>
</employee>

<employee id=2>
<properties Name="firstname">John</properties>
<properties Name="lastname">Watson</properties>
<properties Name="age">30</properties>
<properties Name="department">writing </properties>
</employee>
</employees>

Create table employees
(firstname varchar2(10),
lastname varchar2(10),
age number) ;

这是我的代码:

declare 
v_xml xmltype;
begin 
select xmltype(x.employee_data) into v_xml from xml_data x where id=1;
insert into employees (firstname,lastname,age) 
select firstname,lastname,age from xmltable('/employees/employee[@id=1]')
       passing v_xml
       columns firstname varchar2(30) path '/properties[@firstname]',
               lastname varchar2(30) path '/properties[@lastname]',
               age number path '/properties[@age]');
end;
/

以下输出除外:

员工表:

firstname lastname age
sherlock holmes 30

但没有值被插入到员工表中。

谁能提出一个更好的方法来解决这个问题

【问题讨论】:

    标签: sql xml oracle plsql xmltable


    【解决方案1】:
    • 您不需要 PL/SQL,只需一条 SQL 语句即可完成所有操作。
    • 您需要使用path '/properties[@Name="firstname"]',因为您需要名为Name 且值为firstname 的属性,而不是搜索名为firstname 的属性是否存在。

    例如:

    insert into employees (firstname,lastname,age)
    select firstname,
           lastname,
           age
    from   xml_data d
           CROSS JOIN xmltable(
             '/employees/employee[@id=1]'
             passing XMLTYPE(d.employee_data)
             columns
               firstname varchar2(30) path 'properties[@Name="firstname"]',
               lastname  varchar2(30) path 'properties[@Name="lastname"]',
               age       number       path 'properties[@Name="age"]'
           )
    WHERE  d.id = 1;
    

    此外,您的数据无效,因为您需要引用 XML 元素属性中的值(而不是使用更宽松的 HTML 语法),因此 &lt;employee id=1&gt; 应该是 &lt;employee id="1"&gt;

    db小提琴here

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多