Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating sql code programmatically

i have generated scripts manually through Generate script in tasks menu by right clicking database.

Now my problem is to generate that script through c# code...

My question is

  1. is it possible to generate through c# code?

  2. give me some tips in order to complete?

Waiting for your valuable suggestions and commands.

like image 911
GowthamanSS Avatar asked Aug 27 '12 10:08

GowthamanSS


1 Answers

As it's already mentioned, you cas use SMO to do this, here is a an example using C# to script a database, I mentioned few options, but as it is in the post of @David Brabant, you can specify the values of many options.

public string ScriptDatabase()
{
      var sb = new StringBuilder();

      var server = new Server(@"ServerName");
      var databse = server.Databases["DatabaseName"];

      var scripter = new Scripter(server);
      scripter.Options.ScriptDrops = false;
      scripter.Options.WithDependencies = true;
      scripter.Options.IncludeHeaders = true;
      //And so on ....


      var smoObjects = new Urn[1];
      foreach (Table t in databse.Tables)
      {
          smoObjects[0] = t.Urn;
          if (t.IsSystemObject == false)
          {
              StringCollection sc = scripter.Script(smoObjects);

              foreach (var st in sc)
              {
                  sb.Append(st);
              }
           }
       }
            return sb.ToString();
 }

This link may help you getting and scripting stored procedures

like image 140
SidAhmed Avatar answered Sep 28 '22 01:09

SidAhmed