SQL通过传递参数方式备份数据库.

存储过程的SQL代码:

ALTER PROCEDURE USP_DBBackup

    @BackPath nvarchar(100),    --存储目录.

    @BackName nvarchar(50)    --存储数据库名.

AS

      SET NOCOUNT ON 

 

      declare @name nvarchar(4000)

      select @name = rtrim(ltrim(@name))

 

      if exists (SELECT Name FROM Master..SysDatabases where name = 'PersonnelManagementSystem')    --寻找指定的数据库.

        set @name= 'PersonnelManagementSystem'

 

      declare @outpath nvarchar(4000)

      select @outpath = @BackPath +'\'+ @BackName    --拼接总路径.

 

    backup database @name to disk= @outpath
View Code

Winform中调用存储过程的C#代码:

//备份.

        private void btnBackConfirm_Click(object sender, EventArgs e) {

            string strConn = @"Data Source=.\SQLExpress;Initial Catalog=PersonnelManagementSystem;Integrated Security=True";

            using(SqlConnection connect = new SqlConnection(strConn)) {

                connect.Open();

                using(SqlCommand cmd = connect.CreateCommand()) {

                    cmd.CommandText = "USP_DBBackup";

                    cmd.Parameters.Clear();

                    cmd.Parameters.Add("@BackPath", SqlDbType.NVarChar, 100).Value = txtBackPath.Text.Trim();   //存储路径.

                    cmd.Parameters.Add("@BackName", SqlDbType.NVarChar, 50).Value = txtBackNewDBName.Text.Trim();  //存储数据库名.

                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.ExecuteNonQuery();

                }

            }

            MessageBox.Show("Done!");

        }
View Code

 

你可能感兴趣的:(传递参数)