2

I have this kind of data:

Data

Is it possible to produce this XML file as output with a SQL query from that table?

XML

3
  • I know SQL can give you XML like <data_t><code>subxxx</code><amount>123.00</amount><data_t/>.. but not like the result you expecting Commented Nov 23, 2017 at 9:02
  • Yep. I manage also produce XML file with root and tags - bur receiving side needs file in this format. :/ Commented Nov 23, 2017 at 9:05
  • I personally don't think you can get this with SQL, it seems more than normal XML. Commented Nov 23, 2017 at 9:19

1 Answer 1

3

Not sure what issues you actually had but you need to use for xml path() and nest them in a couple of sub-queries.

declare @T table(code varchar(30), amount money);

insert into @T(code, amount) values
('totalPAS', 389),
('sub270', 0),
('sub770', 0),
('sub270', 0);

select 'datfile' as '@objectCode', 
       (
       select T.code as '@instanceCode',
              'data_t' as '@objectCode',
              (
              select 'code' as 'ColumnValue/@name',
                     T.code as 'ColumnValue',
                     null,
                     'amount' as 'ColumnValue/@name',
                     T.amount as 'ColumnValue'
             for xml path('CustomInformation'), type
             ) 
       from @T as T
       for xml path('instance'), type
       )
for xml path('customObjectInstances');

Result:

Sign up to request clarification or add additional context in comments.

3 Comments

Wow! Worked! Thousand times thank You! One option: If I have so called header information for the file - what would be the easiest way to add that into the result?
@Tsy79 if you are talking about the XML declaration have a look here. stackoverflow.com/questions/5423560/…
Please find my next level question below.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.