将xml数据插入存储过程中的sql表中

时间:2019-04-10 07:18:49

标签: sql-server xml

我想将XML数据插入存储过程中的sql表中。我想插入CNAME和AMOUNT值。如何使用下面的xml实现此目标?

<ENTITY>
<CNAME>
<NAME>FGGFGFGF</NAME>
</CNAME>
<AMOUNT>
<AMOUNT1></AMOUNT1>
<AMOUNT2>67052549.33</AMOUNT2>
</AMOUNT>
<CNAME>
<NAME>FGGFGFGF</NAME>
</CNAME>
<AMOUNT>
<AMOUNT1></AMOUNT1>
<AMOUNT2>67052549.33</AMOUNT2>
</AMOUNT>
</ENTITY> 
INSERT INTO Table1(NAME,AMOUNT1, AMOUNT2) SELECT t.c.value('(NAME)[1]', 'varchar(50)') AS NAME, d.c.value('(AMOUNT1) 
[1]', 'varchar(50)') AS AMOUNT1, d.c.value('(AMOUNT2)[1]','varchar(50)') as 
AMOUNT2 FROM @xmlData.nodes('/ENTITY') m(c) CROSS APPLY m.c.nodes(N'CNAME') 
t(c) CROSS APPLY m.c.nodes(N'AMOUNT') d(c)

1 个答案:

答案 0 :(得分:1)

这应该为您提供所需的结果,请务必检查数据类型

DECLARE @XML AS XML= N'
<ENTITY> 

<CNAME> 
<NAME>FGGFGFGF</NAME> 
</CNAME> 
<AMOUNT> 
<AMOUNT1></AMOUNT1> 
<AMOUNT2>67052549.33</AMOUNT2> 
</AMOUNT> 

<CNAME> 
<NAME>FGGFGFGF</NAME> 
</CNAME> 
<AMOUNT> 
<AMOUNT1>
</AMOUNT1> 
<AMOUNT2>67052549.33</AMOUNT2> 
</AMOUNT>

</ENTITY> '
SELECT   nme.ROWID
        ,nme.NAME
        ,amt.AMOUNT1
        ,amt.AMOUNT2
FROM 
    (
        SELECT   TRY_CONVERT(NVARCHAR(50),nme.value('(NAME/text())[1]',       'VARCHAR(MAX)'))      AS NAME
                ,ROW_NUMBER() OVER (ORDER BY T.nme)                                                 AS ROWID    
        FROM    @XML.nodes('ENTITY/CNAME') AS T(nme) 
    )nme
    LEFT OUTER JOIN
    (
        SELECT   TRY_CONVERT(MONEY,amt.value('(AMOUNT1/text())[1]',           'VARCHAR(MAX)'))      AS AMOUNT1
                ,TRY_CONVERT(MONEY,amt.value('(AMOUNT2/text())[1]',           'VARCHAR(MAX)'))      AS AMOUNT2
                ,ROW_NUMBER() OVER (ORDER BY T.amt)                                                 AS ROWID    
        FROM    @XML.nodes('ENTITY/AMOUNT') AS T(amt) 
    )amt
        ON nme.ROWID = amt.ROWID
OPTION (OPTIMIZE FOR (@XML = NULL))