Question

I can backup a database on hard disk with the following method :

void BackUp(string ConnectionString, string DatabaseFullPath, string backUpPath)
{
    progressBar1.Value = 0;

    using (SqlConnection con = new SqlConnection(ConnectionString))
    {
        con.Open();

        string UseMaster = "USE master";
        SqlCommand UseMasterCommand = new SqlCommand(UseMaster, con);
        UseMasterCommand.ExecuteNonQuery();

        progressBar1.Value += 25;

        string Alter1 = @"ALTER DATABASE [" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
        SqlCommand Alter1Cmd = new SqlCommand(Alter1, con);
        Alter1Cmd.ExecuteNonQuery();

        progressBar1.Value += 25;

        string Restore = @"BACKUP DATABASE [" + DatabaseFullPath + "] TO  DISK = N'" + backUpPath + @"' WITH NOFORMAT, NOINIT,  NAME = N'" + DatabaseFullPath + "-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
        SqlCommand RestoreCmd = new SqlCommand(Restore, con);
        RestoreCmd.ExecuteNonQuery();

        progressBar1.Value += 25;

        string Alter2 = @"ALTER DATABASE [" + DatabaseFullPath + "] SET Multi_User";
        SqlCommand Alter2Cmd = new SqlCommand(Alter2, con);
        Alter2Cmd.ExecuteNonQuery();

        progressBar1.Value += 25;

        labelReport.Text = "Successful";
    }
}

and , How can I convert it to a Stored Procedure ?

(I'm newbie in SQL Server)

Was it helpful?

Solution

If your intent is to encapsulate the backup task in a stored procedure purely so it can be executed from C#, then maybe you want to consider SQL Server Management Objects (SMO) instead? These objects give you programmatic access to SQL Server administration tasks such as performing backups. Check out the second sample here: http://msdn.microsoft.com/en-us/library/ms162133.aspx


Edit: But to answer the question, you can follow this example which works for me:

CREATE PROCEDURE BackupDatabase
(
    @databaseName sysname, 
    @backupPath varchar(260)
)
AS
BEGIN
    BACKUP DATABASE @databaseName 
        TO DISK = @backupPath
        WITH FORMAT;
END
GO

called by

DECLARE @return_value int

EXEC    @return_value = [dbo].[BackupDatabase]
        @databaseName = play,
        @backupPath = N'c:\backup\play.bak'

SELECT  'Return Value' = @return_value

GO
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top