开发者

join multiple 'for XML' outputs in an efficient manner

In the code below, I am join the xml output of two independent select clauses into one XML.

create procedure Test
as

declare @result nvarchar(max)

set @result = '<data>'
set @result = @result + (select FieldA from Table1 for xml raw('a'), root('table1'))
set @result = @result + (select FieldB from Table2 for xml raw('b'), root('table2'))
set @result = @result + '/<data>'

return @result

Output would look like:

<data>
    <table1>
        <a FieldA="01"/>
        <a FieldA="02"/>
    </table1>
    <table2>
        <b FieldB="aa"/>
        <b FieldB="bb"/>
    </table2>
</data>

I 开发者_JAVA技巧would like to know if there is a much better way to achieve the above output with greater Performance.

I believe 'for xml' output (xml data type) is streamed while the nvarchar is not. So, is it beneficial to output as XML data type? or, does Xml datatype overheads (parsing, wellformedness checks, etc) overweight the streaming benefit over nvarchar datatype?

Edit The procedure will be called by an ASP.Net application and results are read through the ADO.Net classes


It is possible to combine xml from subqueries into a bigger xml result. The key is to use the sqlserver xml type.

with foodata as (
  select 1 as n
  union all
  select n+1 from foodata where n < 20
)
select
  (select n as 'text()' from foodata where n between 10 and 13 for xml path('row'), root('query1'), type),
  (select n as 'text()' from foodata where n between 15 and 18 for xml path('row'), root('query2'), type)
for xml path('root'), type

The query above will generate the following output:

<root>
  <query1>
    <row>10</row>
    <row>11</row>
    <row>12</row>
    <row>13</row>
  </query1>
  <query2>
    <row>15</row>
    <row>16</row>
    <row>17</row>
    <row>18</row>
  </query2>
</root>

I can't say which is faster though. You will just have to do some benchmarks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜