pl / sql块

时间:2016-11-25 13:24:32

标签: oracle plsql oracle11g

在常规查询中,我可以使用xmlexists函数查看xmltype列中是否存在特定值。但是当我想在pl / sql块中使用它时,由于语法错误,脚本将无法编译(遇到以下其中一个时遇到符号“传递”...)。

简单的脚本示例:

DECLARE
  v_xml xmltype;
BEGIN
  for rec in (select xmltypecol from mytable where type='XXX')
  loop
    v_xml := rec.xmltypecol;
    if xmlexists('/test[node=(10,12)]' passing v_xml) then
      -- processing 
    end if;                                                          
  end loop;
END;

在pl / sql块中使用xmlexists的正确方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

某些Oracle SELECT XMLELEMENT("number", 123) INTO v_xml FROM dual;函数只能在SQL中使用,而不能在PL / SQL中使用 - 不要问我原因。

例如,DECLARE v_xml xmltype; r INTEGER; BEGIN for rec in (select xmltypecol from mytable where type='XXX') loop v_xml := rec.xmltypecol; SELECT COUNT(*) INTO r FROM dual WHERE xmlexists('/test[node=(10,12)]' passing v_xml); if r = 1 then -- processing end if; end loop; END; 是不可能的,您必须运行DECLARE v_xml xmltype; BEGIN for rec in (select xmltypecol from mytable where type='XXX' AND xmlexists('/test[node=(10,12)]' passing xmltypecol) loop v_xml := rec.xmltypecol; -- processing end loop; END;

试试这个:

{{1}}

受到Boneist回答的启发,你为什么不这样做

{{1}}

答案 1 :(得分:1)

XMLTYPE有自己的方法one of which is existsnode。这意味着您可以避免PL / SQL和SQL之间的上下文切换,如果您使用select ... from dual将呼叫包裹在xmltype_variable.existsnode('<node>')中,则必须执行此操作。

因此,您的代码如下所示:

DECLARE
  v_xml xmltype;
BEGIN
  for rec in (select xmltypecol from mytable where type='XXX')
  loop
    v_xml := rec.xml;
    if v_xml.xmlexists('/test[node=(10,12)]') = 1 then
      -- processing 
    end if;                                                          
  end loop;
END;

然而,是什么阻止你在光标中进行检查?如果您只对符合条件的行进行处理,那么在查询中进行过滤会不会更好?

此外,如果您的处理涉及DML,您可以使用XMLTABLE生成可以直接连接到DML语句的内容,这样可以一次完成所有处理而不是逐行处理,因此根本不需要光标换环处理?