2015-06-02 44 views
0

我想從xml輸入參數創建一個臨時表。 這是我的XML:sql server 2005使用xml參數創建臨時表

<Offices> 
     <Group id="22807"> 
      <Office>185901</Office> 
      <Office>185902</Office> 
      <Office>185944</Office> 
     </Group> 
    </Offices> 

這是我的SQL:

DECLARE @GroupsOfficeIDs xml 
SET @GroupsOfficeIDs = '<Offices><Group id="22807"><Office>185901</Office><Office>185902</Office><Office>185944</Office></Group></Offices>' 

CREATE TABLE #GroupOfficeID (PK int primary key identity(1,1), IdXml xml) 
INSERT INTO #GroupOfficeID VALUES (@GroupsOfficeIDs) 
SELECT PK, 
group.ref.value('@id', 'int') AS GroupID, 
group.ref.value('(Office/text())[1]', 'varchar(20)') AS OfficeID 
FROM #GroupOfficeID go cross apply go.IdXml.nodes('/Offices/Group') group(ref) 

這將返回1行:

PK GroupID  OfficeID 
1 22807  185901 

我想它返回如下:

PK GroupID  OfficeID 
    1 22807  185901 
    2 22807  185902 
    3 22807  185944 

是我的XM L這是錯誤的或我的查詢? 謝謝!

UPDATE 我遠一點...... 我現在查詢是這樣的:

DECLARE @GroupsOfficeIDs xml 
SET @GroupsOfficeIDs = '<Offices><Group id="22807"><Office>185901</Office><Office>185902</Office><Office>185944</Office></Group></Offices>' 

CREATE TABLE #GroupOfficeID (PK int primary key identity(1,1), IdXml xml) 
INSERT INTO #GroupOfficeID VALUES (@GroupsOfficeIDs) 
SELECT PK, 
group.ref.value('@id', 'int') AS GroupID, 
office.ref.value('(Office/text())[1]', 'varchar(20)') AS OfficeID 
FROM #GroupOfficeID go cross apply go.IdXml.nodes('/Offices/Group') group(ref) 
cross apply go.IdXml.nodes('/Offices/Group/Office') as office(ref) 

它產生這樣的:

PK GroupID  OfficeID 
1 22807  185901 
1 22807  185902 
1 22807  185944 

爲什麼不主鍵增量由1?

+0

你被它給一個結果ID分組。 – jdweng

+0

我在哪裏按ID分組? –

+0

重新閱讀發佈。看起來不像分組是問題。你是正確的PK沒有得到增加。您必須創建一個自動遞增主鍵PK的過程。 – jdweng

回答

1

你得到了相同的價值PK,因爲在一排有一個PK,這意味着來自同一個XML源中的所有數據都將具有相同的主鍵的臨時表中存儲一個XML數據:

CREATE TABLE #GroupOfficeID (PK int primary key identity(1,1), IdXml xml) 
           -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
           -- here you associate one XML data to one identity id 

您可能要改變臨時表結構來存儲一個GroupID - OfficeID組合一行改爲:

CREATE TABLE #GroupOfficeID (PK int primary key identity(1,1), GroupID int, OfficeID int) 

那麼對於插入查詢會像這樣(避免使用關鍵字像GOGROUP別名)!

INSERT INTO #GroupOfficeID(GroupID,OfficeID) 
SELECT 
    g.value('@id','int') GroupID, 
    o.value('.','int') OfficeID 
FROM @GroupsOfficeIDs.nodes('/Offices/Group') grp(g) 
    CROSS APPLY g.nodes('Office') office(o) 

然後SELECT * FROM #GroupOfficeID會產生正確的預期結果:

PK GroupID  OfficeID 
1 22807  185901 
2 22807  185902 
3 22807  185944 

SQL Fiddle Demo

+0

謝謝。這工作。 BTW..didn't不知道有這樣的事情,SQL小提琴! –

+0

不客氣。是的,這對於SQL問題非常有用:[提出一個好的結構化查詢語言(SQL)問題的提示](http://meta.stackoverflow.com/a/271056/2998271) – har07

相關問題