我想从SQL Server 2005查询多个表并创建一个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
答案 0 :(得分:11)
如果你想要一个接一个,你可以尝试这样的事情:
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>
答案 1 :(得分: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
答案 2 :(得分: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>