Link to home
Start Free TrialLog in
Avatar of andre72
andre72

asked on

Write data from SQL Server 2008 to XML file using C#

Hi,

I like to get the stucture from a SQL Server 2008 table, here's my idea about:
SELECT C.COLUMN_NAME AS [Column]
FROM INFORMATION_SCHEMA.Tables T JOIN INFORMATION_SCHEMA.Columns C
ON T.TABLE_NAME = C.TABLE_NAME
WHERE T.TABLE_NAME ='person'

Output:
FirstName
LastName

Now I like to get all data from the table:
SELECT * FROM 'person'

Output:
John | Doe
Fred | Smith

My output should looks like:
<Table>
   <Person>
     <FirstName>John</FirstName>
     <LastName>Doe</LastName>
   </Person>
   <Person>
    <FirstName>Fred</FirstName>
     <LastName>Smith</LastName>
   </Person>
</Table>

The only idea I would have to make some C# code with many loops:
foreach() // all rows
{
// write start element
foreach() // all columns
{
   // write element
}
}

For sure I think this will work but do you've any better solution for because I think with big tables it'll need a lot of time for ...

Thanks,

Andre
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Have you looked at the FOR XML clause?
What about reading data into a DataSet and saving it in a XML format?

Have a look:
http://msdn.microsoft.com/en-us/library/zx8h06sz.aspx

If you need to write just separate tables you can do so:
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic39227.aspx

Just be aware you may loose some data if you have relations etc.
Avatar of andre72
andre72

ASKER

@acperkins
No, I don't now about. Do you have a URL in the net with some information about?

@anarki jimbel
Looks very intresting - I'll have a look for

Thanks,

Andre
Avatar of andre72

ASKER

Thanks rrjegan17 - any way to save this to a file than?
Yes you have..
In your SSMS, Click Query in Menu --> Results to --> Results to File.

When you run the query it will save the resultset in a file.
Rename that *.rpt file to *.xml and that's done.
Avatar of andre72

ASKER

No, I'm sorry about for missunderstanding - I need to do this programmatically ...
ASKER CERTIFIED SOLUTION
Avatar of Raja Jegan R
Raja Jegan R
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial