Search code examples
sql-serverxmlt-sqlxquery

T-SQL - XML TAG DESCRIPTION + VALUE


I can't receive XML in this format:

<ROOT>
    <Test ColA="A">B</Test>
</ROOT>

This what I have:

select 'A' as ColumnA, 'B' as ColumnB into _Atest
select ColumnA as [Test/@A]
from _Atest
for XML PATH (''), root ('ROOT')

And output are:

<ROOT>
  <Test A="A" />
</ROOT>

How I can receive:

<ROOT>
    <Test ColA="A">B</Test>
</ROOT>

"A" - value from ColumnA B - value from ColumnB


Solution

  • Please try the following.

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ColumnA CHAR(1), ColumnB CHAR(1));
    INSERT INTO @tbl (ColumnA, ColumnB) VALUES
    ('A', 'B');
    -- DDL and sample data population, end
    
    SELECT ColumnA AS [Test/@ColA]
        , ColumnB AS [Test]
    FROM @tbl
    FOR XML PATH(''), TYPE, ROOT('ROOT');
    

    Output

    <ROOT>
      <Test ColA="A">B</Test>
    </ROOT>