2012-08-09 91 views
4

我想從SQL Server 2005中查詢多個表並創建一個XML文檔並在存儲過程中執行此操作。從SQL Server多表創建單個XML查詢

我知道我可以查詢存儲過程中的多個表,並在我的.NET應用程序中獲得DataSet,該應用程序可以輕鬆地保存爲XML。但是,我試圖在存儲過程的上下文中做類似的事情。

基本上我想要做這樣的事情:如果你希望他們後,其他只是一個

declare @x xml 
select @x = x.result 
from (select y.* from tabley y for xml path('y') 
     union 
     select a.* from tablea a for xml path('aa') 
    ) as x 
select @x 

回答

10

,你可以嘗試這樣的事:

SELECT 
    (SELECT y.* FROM dbo.TableY FOR XML PATH('y'), TYPE) AS 'YElements', 
    (SELECT a.* FROM dbo.TableA FOR XML PATH('aa'), TYPE) AS 'AElements' 
FOR XML PATH(''), ROOT('root') 

返回的XML像:

<root> 
    <YElements> 
    <Y> 
     .... 
    </Y> 
    <Y> 
     .... 
    </Y> 
     ...... 
    </YElements> 
    <AElements> 
    <A> 
     .... 
    </A> 
    <A> 
     .... 
    </A> 
     ...... 
    </AElements> 
</root> 
+0

謝謝,我試圖做一個工會,而不是使用逗號 – BermudaLamb 2012-08-09 18:11:45

0

在sql server中轉換表XML。

Declare @RESULTXML XML 
Declare @SMS_REGISTER TABLE([id] VARCHAR(30),[status] VARCHAR(30)) 
Declare @EMAIL_REGISTER TABLE([id] VARCHAR(30),[status] VARCHAR(30)) 
Declare @ODP_REGISTER TABLE([id] VARCHAR(30),[status] VARCHAR(30)) 

Select @RESULTXML =( 
SELECT (SELECT * FROM @SMS_REGISTER FOR XML PATH('sms'), TYPE) AS 'smss', 
     (SELECT * FROM @EMAIL_REGISTER FOR XML PATH('email'), TYPE) AS   'emails', 
     (SELECT * FROM @ODP_REGISTER FOR XML PATH('odp'), TYPE) AS 'odps' 
    FOR XML PATH('subroot'), ROOT('root')) 

返回這樣的XML

 
    <root> 
     <subroot> 
     <smss> 
      <sms> 
      <id>NT0000000020</id> 
      <status>registered</status> 
      </sms> 
      <sms> 
      <id>NT0000000021</id> 
      <status>registered</status> 
      </sms> 
      <sms> 
      <id>NT0000000022</id> 
      <status>registered</status> 
      </sms> 
      <sms> 
      <id>NT0000000023</id> 
      <status>registered</status> 
      </sms> 
     </smss> 
     <emails> 
      <email> 
      <id>NT0000000024</id> 
      <status>registered</status> 
      </email> 
      <email> 
      <id>NT0000000025</id> 
      <status>registered</status> 
      </email> 
     </emails> 
     </subroot> 
    </root> 

1
SELECT                -- Root Starts 
    (SELECT '1' AS ErrorCode FOR XML PATH(''), TYPE) AS 'Results', -- Level 1 Starts 
     (select              -- Level 2 Starts 
      (select  '1'   CustomerID,     -- Level 2 Detail Starts 
          'John'  CustomerName, 
          'Doe'  CustomerLastname, 
          'Y'   Active 
       for xml path('Customers'), type) AS 'Customer'   -- Level 2 Detail Ends 
     for xml path(''), TYPE) AS 'Response'       -- Level 2 Ends 
    FOR XML PATH('')             -- Level 1 Ends 
,ROOT('BaseXML')              -- Root Ends