我有一个xml文档,我想将其作为参数传递给存储过程 xml看起来像这样
<root>
<EMPLOYEE ID= 100>
<PERIOD>AUG-2010</PERIOD>
<earnings>
<title>BASIC</title>
<amount>2000</amount>
<title>HRA</title>
<amount>1000</amount>
<title>CONVEYANCE</title>
<amount>500</amount>
</earnings>
</EMPLOYEE>
<EMPLOYEE ID= 101>
<PERIOD>AUG-2010</PERIOD>
<earnings>
<title>BASIC</title>
<amount>2000</amount>
<title>HRA</title>
<amount>400</amount>
<title>CONVEYANCE</title>
<amount>500</amount>
</earnings>
</EMPLOYEE>
<EMPLOYEE ID= 102>
<PERIOD>AUG-2010</PERIOD>
<earnings>
<title>BASIC</title>
<amount>2000</amount>
<title>HRA</title>
<amount>800</amount>
<title>CONVEYANCE</title>
<amount>5000</amount>
</earnings>
</EMPLOYEE>
</root>
我需要将上述信息存储到2个表中,即:payslipdetails和payheaddetails。 我想我必须遍历xml doc。外部循环给了我员工ID和句点,然后我插入带有这些字段的payslipdetails表,然后进入内部循环,我想插入payheaddetails与相同的employeeid和他所有的收入deatls像
empid title amount
100 basic 2000
100 hra 1000
100 conveyance 500
然后我转到外部循环并获得下一个员工ID并重复相同的事情
我怎样才能像openxml等那样去内部子xml。??
答案 0 :(得分:0)
首先,这是不有效的XML:
<EMPLOYEE ID= 102>
<PERIOD>AUG-2010</PERIOD>
<earnings>
<title>BASIC</title>
<amount>2000</amount>
<title>HRA</title>
<amount>800</amount>
<title>CONVEYANCE</title>
<amount>5000</amount>
</earnings>
</EMPLOYEE>
ID=
属性必须紧跟数据 - 最好是双引号 - 这是有效的:
<EMPLOYEE ID="102">
下一步:你的<title>..</title><amount>...</amount>
标签内有多个<earnings>
标签对但没有容器的事实使得解析旁边不可能(或者非常混乱)......
<earnings>
<title>BASIC</title>
<amount>2000</amount>
<title>HRA</title>
<amount>800</amount>
<title>CONVEYANCE</title>
<amount>5000</amount>
</earnings>
如果可能,请尝试将其更改为:
<earnings>
<earning>
<title>BASIC</title>
<amount>2000</amount>
</earning>
<earning>
<title>HRA</title>
<amount>800</amount>
</earning>
<earning>
<title>CONVEYANCE</title>
<amount>5000</amount>
</earning>
</earnings>
这将更容易来处理!
如果 包含<earning>
对的额外<title>/<amount>
容器,那么您可以轻松编写此XQuery语句并处理所有需求而无需杂乱,缓慢的游标:
SELECT
RootData.Employee.value('(@ID)[1]', 'int') AS 'EmployeeID',
E.E2.value('(title)[1]', 'varchar(50)') AS 'Title',
E.E2.value('(amount)[1]', 'decimal(18,4)') AS 'Amount'
from
(your XML column).nodes('/root/EMPLOYEE') AS RootData(Employee)
CROSS APPLY
RootData.Employee.nodes('earnings/earning') AS E(E2)
你会得到这样的输出:
EmployeeID Title Amount
100 BASIC 2000.0000
100 HRA 1000.0000
100 CONVEYANCE 500.0000
101 BASIC 2000.0000
101 HRA 400.0000
101 CONVEYANCE 500.0000
102 BASIC 2000.0000
102 HRA 800.0000
102 CONVEYANCE 5000.0000