2010-11-02 104 views
0

我有我想作爲參數 的XML看起來像這樣解析XML文檔SQL服務器內存儲的過程

<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> 

傳遞到存儲過程的xml文檔我需要存儲上述信息到2表,即:工資單和payheaddetails。 我想我必須循環訪問xml文檔。外環給我的員工ID和週期,然後我插入payslipdetails表的字段,然後進入內循環,我想插入payheaddetailswith同僱員和他的所有收入deatls像

empid title amount 
100  basic 2000 
100  hra  1000 
100  conveyance 500 

然後我去外部循環,並獲得下一個員工ID並重復相同的事情

我怎麼能去像內部的孩子XML任何方式像openxml等.. ??

回答

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"> 

下一頁:在<earnings>標記內部沒有容器的情況下,您有多個<title>..</title><amount>...</amount>標記對,這使得解析幾乎不可能(或者真的很麻煩).....

<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