T-SQL:如何选择行作为XML元素

时间:2016-01-07 17:32:50

标签: sql-server xml tsql for-xml

我有桌子

   Cost       RenderedValue    SectionName
   ------------------------------------
  100.00      1000.00          Section1
  200.00      2000.00          Section2
  300.00      3000.00          Section3
  400.00      4000.00          Section4

我想生成这个XML:

<Root>
   <Section1Cost>100.00</Section1Cost>
   <Section1RenderedValue>1000.00</Section1RenderedValue>
   <Section2Cost>200.00</Section2Cost>
   <Section2RendredValue>2000.00</Section2RendredValue>
</Root>

我能够使用TSQL(Test is my table name)生成它

SELECT
    (SELECT Cost AS 'Cost'FROM Test WHERE SectionName = 'Section1') AS 'Section1Cost',
    (SELECT RenderedValue AS 'Cost'FROM Test WHERE SectionName = 'Section1') AS 'Section1RenderedValue',
    (SELECT Cost AS 'Cost'FROM Test WHERE SectionName = 'Section2') AS 'Section2Cost',
    (SELECT RenderedValue AS 'Cost'FROM Test WHERE SectionName = 'Section2') AS 'Section2RendredValue'
FOR XML Path(''), Root('Root')

但这很难看,我认为它没有优化。它可以更优雅,还是我所拥有的任何东西都是正确的?

我可能在该测试表中最多有30行

3 个答案:

答案 0 :(得分:0)

这为您提供了略微不同的XML(使用Section标签),但SQL脚本应该更有效:

SELECT
    Test.SectionName AS [@SectionName],
    Test.Cost AS [Cost],
    Test.RenderedValue AS [RenderedValue]

FROM Test
ORDER BY Test.SectionName
FOR XML PATH ('Section'), ROOT('Sections');

这是您提供的示例表的脚本输出:

<Sections><Section SectionName="Section1"><Cost>100.0000</Cost><RenderedValue>1000.0000</RenderedValue></Section><Section SectionName="Section2"><Cost>200.0000</Cost><RenderedValue>2000.0000</RenderedValue></Section><Section SectionName="Section3"><Cost>300.0000</Cost><RenderedValue>3000.0000</RenderedValue></Section><Section SectionName="Section4"><Cost>400.0000</Cost><RenderedValue>4000.0000</RenderedValue></Section></Sections>

答案 1 :(得分:0)

我想我明白了

<强> EDIT1

我想收回我所说的内容,我提到的解决方案并不完全符合我的要求。当记录不存在时我想打印0.所以如果修改上面的那就不行了

 select 
 case when t.sectionname = 'section1' then t.cost else 0 end as 'section1cost',
 case when t.sectionname = 'section1' then t.renderedvalue else 0 end as 'section1rendervalue'
 from test t
 for xml path(''),root('root')

答案 2 :(得分:0)

嗨,这是我之前回答的修改版本,基于您的最新答案user3862378

DECLARE @sql varchar(max) = ''
DECLARE @case VARCHAR(MAX) = ''

SELECT  @case += 'case when t.sectionname = '''+SectionName+''' then t.cost  end as '''+SectionName+'Cost'',
 case when t.sectionname = '''+SectionName+''' then t.renderedvalue  end as '''+SectionName+'RenderedValue'','

  FROM <YOUR TABLE NAME>

  SELECT @sql = 'select '+ SUBSTRING(@case,1,LEN(@case)-1) +'from <YOUR TABLE NAME> t
 for xml path(''''),root(''root'')'

 EXECUTE (@sql)

以下是结果:

<root>
  <Section1Cost>100.00</Section1Cost>
  <Section1RenderedValue>1000.00</Section1RenderedValue>
  <Section2Cost>200.00</Section2Cost>
  <Section2RenderedValue>2000.00</Section2RenderedValue>
  <Section3Cost>300.00</Section3Cost>
  <Section3RenderedValue>3000.00</Section3RenderedValue>
  <Section4Cost>400.00</Section4Cost>
  <Section4RenderedValue>4000.00</Section4RenderedValue>
</root>