Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export multiple tables from SQL Server to XML for restore

I have a web application in C# / ASP.NET. I want to export all the database table's data, with the same unique key (Company ID). All the tables have this key (different for every company). I want to do that for future backup. Is it possible with Linq or classic C#? How can achieve this backup and restore?

like image 835
Equilibrium Avatar asked Nov 25 '22 01:11

Equilibrium


1 Answers

One of the example to the solution is

using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace ConsoleApplication4
{
class Program
{
    static void Main(string[] args)
    {
        var connStr = "Data Source=MOHSINWIN8PRO\\SQLEXPRESS;Initial Catalog=AB2EDEMO;Integrated Security=True";
        var xmlFileData = "";
        DataSet ds = new DataSet();
        var tables = new[] {"Hospital", "Patient"};
        foreach (var table in tables)
        {

            var query = "SELECT * FROM "+ table +" WHERE (Hospital_Code = 'Hosp1')";
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(query, conn);
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            conn.Close();
            conn.Dispose();
            xmlFileData+=ds.GetXml();
        }
        File.WriteAllText("D://SelectiveDatabaseBackup.xml",xmlFileData);
    }
}

}

this will create SelectiveDatabaseBackup.xml which can be later used to restore the backup

like image 76
Syed Mohd Mohsin Akhtar Avatar answered May 25 '23 01:05

Syed Mohd Mohsin Akhtar