Pergunta

I would like to be able to write out an XML file in this specific format. I've been reading up on bcp and experimenting with FOR XML but can't seem to achieve what I need here. I would appreciate any help in the right direction. While I know I could refactor the code that would consume this XML output; I'd like to be adventurous here and stick to the task at hand without changing anything.

SQL code for recreating a temp var table dataset

declare @dataset table(Color nvarchar(10), Number int, Code nvarchar(10))

insert into @dataset 
  select 'Green', 12345, 'US1'
  union
  select 'Red', 56789, 'US2'

select * from @dataset

And from this query I would like to generate the following XML document.

<?xml version="1.0" encoding="utf-8" ?>
<test>
  <collection>
    <Case>
      <input>
        <attribute name="Color">Green</attribute>
        <attribute name="Number">12345</attribute>
        <attribute name="Code">US1</attribute>
      </input>
    </Case>
    <Case>
      <input>
        <attribute name="Color">Red</attribute>
        <attribute name="Number">56789</attribute>
        <attribute name="Code">US2</attribute>
      </input>
    </Case>
  </collection>
</test>

I will defer to you experts to tell me if this is too ridiculous to be accomplished, but I think it "is" possible as I've got a little close so far.

I've been tinkering with this and able to write out XML files.

exec master..xp_cmdshell 'bcp "Query Here" queryout "c:\filename.xml" -c -T'

Thanks SO members!

Foi útil?

Solução

select (
       select (
              select 'Color' as [attribute/@name],
                     Color as [attribute],
                     null,
                     'Number' as [attribute/@name],
                     Number as [attribute],
                     null,
                     'Code' as [attribute/@name],
                     Code as [attribute]
              for xml path('input'), type 
              ) 
       from @dataset
       for xml path('Case'), root('collection'), type
       )
for xml path('test'), type
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top