What is SMO?


SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server.

We can integrate SMO into any .NET based applications.

SMO is also compatible with SQL Server version 7.0, SQL Server 2000, and SQL Server 2005, which makes it easy to manage a multi-version environment.

Following code is used to run the Microsoft SQL Server Query files(script files) kept in applications bin\Debug folder, with SMO.

C# Code:

//Add refrence Microsoft.Sqlserver.Smo .dll;
using Microsoft.SqlServer.Management.Smo;
//Add refrence Microsoft.SqlServer.ConnectionInfo .dll;
using Microsoft.SqlServer.Management.Common;

        string tableText = string.Empty;
        tableText = Server.MapPath(@"~\ScriptFile\")+"TableScripts.sql";
        Server s = new Server();
        ServerConnection svrCon;
        Database objDb=s.Databases["MyDB"];
        svrCon = s.ConnectionContext;
        svrCon.ServerInstance = "serverName";
        svrCon.LoginSecure = false;
        if (svrCon.LoginSecure == false)
        {
            svrCon.Login = "";
            svrCon.Password = "";
        }
      using (Microsoft.VisualBasic.FileIO.TextFieldParser FileReader=new Microsoft.VisualBasic.FileIO.TextFieldParser("")){
          tableText = FileReader.ReadToEnd();
      }
      if (string.IsNullOrEmpty(tableText))
      {
          objDb.ExecuteNonQuery(tableText);
      }
    }


Similar Articles