1

How to take Backup SQL Server 2008 database to a sql file(like .sql) using c#

I am creating a program that uses a simple database with only a few tables. I need to do a backup and restore of the database to and from a SQLfile like a .SQL. How can i do it..

Thank You

4
  • 1
    Do you mean that you want the backup to be a .sql file with statements like create database X; create table Y (...); insert into y values (...) ? Commented Oct 15, 2013 at 10:31
  • If you want to create a dump file as in mysql it is better to use SQL Server Management Objects Commented Oct 15, 2013 at 10:35
  • @LasseVågsætherKarlsen I want the same as you said. can you help me? Commented Aug 26, 2019 at 7:51
  • @MuhammadWaheed I don't know how to do that for SQL Server, I only asked a clarification question as he mentions a backup format extension of .sql, which is usually reserved for text files with sql statements. Commented Aug 26, 2019 at 8:24

2 Answers 2

2

You can take the database backup using SQL Server backup wizard or using SQL Server BackUp Database statement

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.

For taking the database backup using C#, you have to add the following references in your application-

Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoExtended
Microsoft.SqlServer.SqlEnum

In your .CS file you will have to use the following namespaces-

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

After using above namespaces, write the following code to take the database backup-

public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
    {
        //Define a Backup object variable.
        Backup sqlBackup = new Backup();

        //Specify the type of backup, the description, the name, and the database to be backed up.
        sqlBackup.Action = BackupActionType.Database;
        sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
        sqlBackup.BackupSetName = "FullBackUp";
        sqlBackup.Database = databaseName;

        //Declare a BackupDeviceItem
        BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
        //Define Server connection
        ServerConnection connection = new ServerConnection(serverName, userName, password);
        //To Avoid TimeOut Exception
        Server sqlServer = new Server(connection);
        sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
        Database db = sqlServer.Databases[databaseName];

        sqlBackup.Initialize = true;
        sqlBackup.Checksum = true;
        sqlBackup.ContinueAfterError = true;

        //Add the device to the Backup object.
        sqlBackup.Devices.Add(deviceItem);
        //Set the Incremental property to False to specify that this is a full database backup.
        sqlBackup.Incremental = false;

        sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
        //Specify that the log must be truncated after the backup is complete.
        sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

        sqlBackup.FormatMedia = false;
        //Run SqlBackup to perform the full database backup on the instance of SQL Server.
        sqlBackup.SqlBackup(sqlServer);
        //Remove the backup device from the Backup object.
        sqlBackup.Devices.Remove(deviceItem);
    }

Use SQL Server's Generate Scripts commend

right click on the database; Tasks -> Generate Scripts

  1. select your tables, click Next
  2. click the Advanced button
  3. find Types of data to script - choose Schema and Data.
  4. you can then choose to save to file, or put in new query window.
  5. results in CREATE and INSERT statements for all table data selected in bullet 2.

see this image

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

6 Comments

If you are going to deal only with sql server it is not advised to use .sql files for backup
SQl backup has extension .bak and not .sql. Thats it! You can use RESTORE to get your backup into db or follow the example that has been given by Aravind or this one: stackoverflow.com/questions/6943137/…
i want to code because i want to get sql format backup file using c#
@user2882066: there IS NO .sql format backup functionality in SQL Server ....
@marc_s there is .sql format for backing up the create structure of tables or database.
|
0

try this

 try
                {
                StringBuilder resultScript = new StringBuilder(string.Empty);
                StringBuilder resultScript1 = new StringBuilder(string.Empty);
                var connStr = @"Data Source=.;Initial Catalog=MatrixEPOS;Integrated Security=True";
                var tables = new[] { "tblProductName", "tblProductSize", "tblProductType", "tblcheck", "tblcheckdetails", "tblSubProduct", "tblMeals", "tblMealDetails",
                "tblMealSizes","tblToppings","tblToppings1","tblToppingsSize","tblDressingSize"};
                ScriptingOptions scriptOptions = new ScriptingOptions();
                Server srv1 = new Server(".");
                Database db1 = srv1.Databases["MatrixEPOS"];
                StringBuilder sb = new StringBuilder();
                Urn[] ur;
                resultScript.AppendLine("Use MatrixEPOS");
                resultScript.AppendLine("GO");
                for(int i = 0; i < tables.Length; i++)
                    {

                    //  Table tbl = db1.Tables[tables[i]];
                    Scripter scr = new Scripter(srv1);

                    foreach(Table table in db1.Tables)
                        {
                        if(table.Name == tables[i].ToString())
                            {
                            // Only include lookup tables
                            if(table.ForeignKeys.Count == 0)
                                {
                                ScriptingOptions options = new ScriptingOptions();
                                options.DriAll = false;
                                options.ScriptSchema = false;
                                options.ScriptData = true;
                                scr.Options = options;

                                // Add script to file content 
                                foreach(string scriptLine in scr.EnumScript(new Urn[] { table.Urn }))
                                    {
                                    string line = scriptLine;
                                    line = line.Replace("SET ANSI_NULLS ON", string.Empty);
                                    line = line.Replace("SET QUOTED_IDENTIFIER ON", string.Empty);
                                    line = line.Replace("SET ANSI_NULLS OFF", string.Empty);
                                    line = line.Replace("SET QUOTED_IDENTIFIER OFF", string.Empty);
                                    resultScript.AppendLine(line.Trim());
                                    }
                                //resultScript1.AppendLine(table.Name);
                                //ur = table.Urn;
                                }
                            }
                        else { }
                        }
                    }
                string name12 = resultScript1 + ".sql";
                string fileName = string.Format("{0}.sql", "abc");
                File.WriteAllText(Path.Combine("G:\\", fileName), resultScript.ToString());
                }
            catch(Exception err)
                {
                Console.WriteLine(err.Message);
                }

i was wasting my 2 days on this hope its helpfull for u

and important thing don't forgot to add reference

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Smo;

Comments

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.