SQL:从XMLTYPE获取值

时间:2018-04-25 18:45:17

标签: sql xml plsql

您能告诉我如何打印供应商站点值1254和90。 它可以是2个或3个或更多站点,因此我需要打印所有站点。

DECLARE

vendor_xml xmltype :=  
    xmltype( 
        '<VENDORLIST> 
            <VENDOR> 
                <VENDOR_NAME>Testvendorname</VENDOR_NAME> 
                <SITE>
                   <ERPSITEID>1254</ERPSITEID>
                </SITE>
                <SITE>
                   <ERPSITEID>90</ERPSITEID>
                </SITE>                   
            </VENDOR> 
        </VENDORLIST>'); 

vendor_name varchar2(100); 
vendor_site number(5); 

cursor cur_sites
IS
SELECT XMLCAST(XMLQUERY('/VENDORLIST/VENDOR/SITE/ERPSITEID' PASSING vendor_xml RETURNING CONTENT) AS number(5)) "REFERENCE"
FROM dual;

BEGIN

FOR i IN cur_sites
LOOP  
   dbms_output.put_line('v-site    :  ' || i.reference); 
END LOOP;    

END;

你能建议吗。

由于 PRAJ

1 个答案:

答案 0 :(得分:1)

你可以这样做:

DECLARE
    vendor_xml   XMLTYPE := xmltype(
        '<VENDORLIST> 
            <VENDOR> 
                <VENDOR_NAME>Testvendorname</VENDOR_NAME> 
                <SITE>
                   <ERPSITEID>1254</ERPSITEID>
                </SITE>
                <SITE>
                   <ERPSITEID>90</ERPSITEID>
                </SITE>
            </VENDOR> 
        </VENDORLIST>');

    CURSOR cur 
    IS 
    SELECT vendor_site
      FROM  XMLTABLE ( '*/VENDOR/SITE' 
            PASSING vendor_xml 
            COLUMNS vendor_site NUMBER PATH 'ERPSITEID' );

BEGIN
    FOR i IN cur LOOP
        dbms_output.put_line('v-site: ' || i.vendor_site);
    END LOOP;
END;
/

如果您想考虑主 - 细节关系,可以这样做:

DECLARE
    vendor_xml   XMLTYPE := xmltype(
        '<VENDORLIST> 
            <VENDOR> 
                <VENDOR_NAME>Testvendorname</VENDOR_NAME> 
                <SITE>
                   <ERPSITEID>1254</ERPSITEID>
                </SITE>
                <SITE>
                   <ERPSITEID>90</ERPSITEID>
                </SITE>
            </VENDOR> 
            <VENDOR> 
                <VENDOR_NAME>Vendor2</VENDOR_NAME> 
                <SITE>
                   <ERPSITEID>4711</ERPSITEID>
                </SITE>
                <SITE>
                   <ERPSITEID>123</ERPSITEID>
                </SITE>
            </VENDOR> 
        </VENDORLIST>');

    CURSOR cur 
    IS 
    SELECT v.vendor_name, vs.vendor_site
      FROM  XMLTABLE ( '*/VENDOR' 
            PASSING vendor_xml 
            COLUMNS vendor_name VARCHAR2(100) PATH 'VENDOR_NAME'
                  , vendor_sites XMLTYPE PATH 'SITE') v
          , XMLTABLE ( '*' 
            PASSING v.vendor_sites 
            COLUMNS vendor_site NUMBER PATH 'ERPSITEID' ) vs
    ;
BEGIN
    FOR i IN cur LOOP
        dbms_output.put_line('v-name: ' || i.vendor_name || ', v-site: ' || i.vendor_site);
    END LOOP;
END;
/