惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
博客园_首页
WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
酷 壳 – CoolShell
酷 壳 – CoolShell
Y
Y Combinator Blog
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
博客园 - 司徒正美
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
N
Netflix TechBlog - Medium
Martin Fowler
Martin Fowler
宝玉的分享
宝玉的分享
G
Google Developers Blog
Last Week in AI
Last Week in AI

博客园 - hello csharp

[导入]Nhibernate引入自定义Membership和Role 推荐个不错的屏幕捕获程序 测试Google Docs 发布的文章.。。 Guidelines – a hidden feature for the Visual Studio Editor Gridview, ObjectDataSource Making life easy Applied MS Reporting Services 101 using Smart Client Database Provider-based ASP.NET Membership Provider HTMLEditor Provider - How to write a custom provider for ASP.NET 2.0 Firebug-javascript/css/ajax/dom调试器【这款不错】 LiveWriter测试 发布个小软件给大伙玩玩 [js小技巧]鼠标移到图片高亮度显示 dot net html分析类库 系统发邮件测试 Dumbster 【小技巧】如何得到一个网页的所有a标记 herf 链接代码 读新浪博客示例[源代码下载] Intellisense for the NHibernate XML Schemas Develop Reports Using Crystal Reports in .NET 2005 [小技巧]winfrom使用多线程
Automatic Sql Server Backup Utility Using sqlserveragent
hello csharp · 2006-12-11 · via 博客园 - hello csharp

By Joshy George

Introduction

It is a sample C# (VS2005) application for Automatic Sql server Backup Utility using sqlserveragent. I have used SQL-DMO dll. This article will show you how to create a automatic backup in Sql server 2000.

This code should work on any PC use VB.NET and installed SQL Server 2000 (any edition or Client Components for SQL Server 2000.

SQLDMO (Which installed always bt MS SQL Server 2000 or MS SQL Server Client Tools

To do:

1) First Enter Your Sql Server username and password on   corresponding Text Box
2) Set backup Start date & Backup Time
3) After Finishing this then please check manually it will working or not
4) Manual working procedure: 
    1) Run Sql sever enterprise Manager
    2) Select management Option
    3) Open Sql server agent
    4) Open Jobs window
    5) Check whether job item exist or not
    6) Right click on newly created job item then, we will get one 
    7) Popup menu, then select start job
    8) After finish the job then check folder "D:\backup" bkp file created or not

Important Functions

Add reference to SQL-DMO dll

You can do this by right clicking the project in Solution Explorer, then selecting 'Add Reference', COM components and the latest version of "Microsoft SQLDMO Object Library".

Available Server

public void dIsplayServerList(ComboBox cboListName)
        {
            try
            {
                SQLDMO.Application oSQLServerDMOApp = new SQLDMO.Application();
                Info.informationLayer info = new Info.informationLayer();
                
                SQLDMO.NameList oNameList;
                oNameList = oSQLServerDMOApp.ListAvailableSQLServers();
                for (int intIndex = 0; intIndex <= oNameList.Count - 1; intIndex++)
                {
                    if (oNameList.Item(intIndex as object) != null)
                    {
                        cboListName.Items.Add(oNameList.Item(intIndex).ToString());
                    }
                }
                if (cboListName.Items.Count > 0) cboListName.SelectedIndex = 0;
                else cboListName.Text = "(Local)";
            }
            catch 
            {
                
            }

Available databases

public void dIsplayDatabases(ComboBox cboDatabase,Info.informationLayer info)
        {
            try
            {
                SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();

                cboDatabase.Items.Clear();
                SQLServer.Connect(info.strServerName,info.strLoginName,info.strPwd);
                foreach (SQLDMO.Database db in SQLServer.Databases)
                {
                    if (db.Name != null)
                        cboDatabase.Items.Add(db.Name);
                }
                cboDatabase.Sorted = true;
                if (cboDatabase.Items.Count == 0)cboDatabase.Text = "";
            }
            catch (Exception err)
            {
                info.ErrorMessageDataLayer = err.Message;

            }
        }


Create Job on Server Agent :

public void CreateJob_Sql(Info.informationLayer info)
        {
            {
                try
                {
                    SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();
                    SQLDMO.Job SQLJob = new SQLDMO.Job();
                    SQLDMO.JobSchedule SQLSchedule = new SQLDMO.JobSchedule();

                    SQLServer.Connect(info.strServerName, info.strLoginName, info.strPwd);

                    switch (SQLServer.JobServer.Status)
                    {
                        case SQLDMO_SVCSTATUS_TYPE.SQLDMOSvc_Stopped:
                            SQLServer.JobServer.Start();
                            SQLServer.JobServer.AutoStart = true;
                            break;
                    }

                    SQLJob.Name = info.strDatabaseName;
                    SQLJob.Description = "Check and Backup" + info.strDatabaseName;

                    SQLServer.JobServer.Jobs.Add(SQLJob);
                    SQLJob.Category = "Database Maintenance";

                    SQLDMO.JobStep aJobStep = new SQLDMO.JobStep();

                    aJobStep.Name = "Step 2: Backup the Database";
                    aJobStep.StepID = 1;

                    aJobStep.DatabaseName = info.strDatabaseName;

                    aJobStep.SubSystem = "TSQL";
                    //------>>> If BackUp Folder is Not Found then create BackUp Folder.
                                    
                     string   DirectoryName = "D:\BackUp";
                     if (Directory.Exists(DirectoryName)==false)
                     {
                         System.IO.Directory.CreateDirectory(DirectoryName);
                     }
                    //------>>>
                    string sExt;
                    sExt="EXEC master.dbo.xp_sqlmaint '-S " + info.strServerName + " -U " + info.strLoginName + " -P " + 
info.strPwd + "  -D " + info.strDatabaseName + " -CkDB -CkAl -CkCat -BkUpMedia DISK -BkUpDB D:\Backup  -BkExt BAK -DelBkUps 
2weeks -BkUpOnlyIfClean -Rpt D:\Backup\BackDB_Checks.txt'";
                    aJobStep.Command = sExt;
                    aJobStep.OnSuccessAction = SQLDMO_JOBSTEPACTION_TYPE.SQLDMOJobStepAction_QuitWithSuccess;
                    aJobStep.OnFailAction = SQLDMO_JOBSTEPACTION_TYPE.SQLDMOJobStepAction_QuitWithFailure;
                    SQLJob.JobSteps.Add(aJobStep);
                    SQLJob.ApplyToTargetServer(info.strServerName);
                    aJobStep.DoAlter();
                    SQLJob.Refresh();
                    aJobStep.Refresh();

                }
                catch (Exception Err)
                {
                    info.ErrorMessageDataLayer = Err.Message;
                }
            }
        }

Create Job shedule on server Agent:

public void CreateShedule_Sql(Info.informationLayer info)
        {
            try
            {
                //it will take bkp every week 2 day
                SQLDMO.Job SQLJob = new SQLDMO.Job();

                SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();
                SQLDMO.JobSchedule SQLSchedule = new SQLDMO.JobSchedule();

                SQLServer.Connect(info.strServerName, info.strLoginName, info.strPwd);
                SQLJob = SQLServer.JobServer.Jobs.Item(info.strDatabaseName);

                // create a new JobSchedule object
                SQLSchedule.Name = "Weekly Backup";
                SQLSchedule.Schedule.FrequencyType = SQLDMO.SQLDMO_FREQUENCY_TYPE.SQLDMOFreq_Weekly;
                SQLSchedule.Schedule.FrequencyInterval = 2;
                SQLSchedule.Schedule.FrequencyRecurrenceFactor = 2; 

                // // start on Feb18, 2000 - at 12.55
                SQLSchedule.Schedule.ActiveStartDate = info.intStartDate;
                SQLSchedule.Schedule.ActiveStartTimeOfDay = info.intStartTime;
                ////  this schedule has no end time or end date

                SQLSchedule.Schedule.ActiveEndDate = 99991231;
                SQLSchedule.Schedule.ActiveEndTimeOfDay = 235959;

                ////  add the schedule to the Job
                SQLJob.BeginAlter();
                SQLJob.JobSchedules.Add(SQLSchedule);
                SQLJob.DoAlter();
                //SQLJob.JobSchedules.Refresh();
                info.ErrorMessageDataLayer = "New Sql Job [Databasename= " + info.strDatabaseName + " ]Sucessfully Created.  ";
            }
            catch (Exception err)
            {
                info.ErrorMessageDataLayer = err.Message;

            }
        }


Syntax (SQL Server 2000)
xp_sqlmaint 'switch_string'
[
    [-S server_name[\instance_name]]
    [-U login_ID [-P password]]
    {
        [ -D database_name | -PlanName name | -PlanID guid ]
        [-Rpt text_file]
        [-To operator_name]
        [-HtmlRpt html_file [-DelHtmlRpt ] ]
        [-RmUnusedSpace threshold_percent free_percent]
        [-CkDB | -CkDBNoIdx]
        [-CkAl | -CkAlNoIdx]
        [-CkCat]
        [-UpdOptiStats sample_percent]
        [-RebldIdx free_space]
        [-WriteHistory]
        [
            {-BkUpDB [backup_path] | -BkUpLog [backup_path] }
            {-BkUpMedia
                {DISK [    [-DelBkUps ] 
                            [-CrBkSubDir ] [ -UseDefDir ]
                         ]
                | TAPE
                }
            }
            [-BkUpOnlyIfClean]
            [-VrfyBackup]
        ]
    }
]

time_period
number[minutes | hours | days | weeks | months]

Syntax (SQL Server 7.0)
sqlmaint 
[-?] |
[
    [-S server]
    [-U login_ID [-P password]]
    {
        [ -D database_name | -PlanName name | -PlanID guid ]
        [-Rpt text_file [-DelTxtRpt ] ]
        [-To operator_name]
        [-HtmlRpt html_file [-DelHtmlRpt ] ]
        [-RmUnusedSpace threshold_percent free_percent]
        [-CkDB | -CkDBNoIdx]
        [-CkAl | -CkAlNoIdx]
        [-CkTxtAl]
        [-CkCat]
        [-UpdSts]
        [-UpdOptiStats sample_percent]
        [-RebldIdx free_space]
        [-WriteHistory]
        [
            {-BkUpDB [backup_path] | -BkUpLog [backup_path] }
            {-BkUpMedia
                {DISK [    [-DelBkUps ] 
                            [-CrBkSubDir ] [ -UseDefDir ]
                         ]
                | TAPE
                }
            }
            [-BkUpOnlyIfClean]
            [-VrfyBackup]
        ]
    }
]

Download dbMaintain.zip